diff --git a/.clang-format b/.clang-format index 16ed32daf284..39a366ebbe9d 100644 --- a/.clang-format +++ b/.clang-format @@ -1,4 +1,5 @@ BasedOnStyle: Google +ColumnLimit: 80 # Prevent the loss of indentation with these macros MacroBlockBegin: "^\ diff --git a/accessible/xpcom/xpcAccessibleMacInterface.mm b/accessible/xpcom/xpcAccessibleMacInterface.mm index a266791579b8..e05937360b61 100644 --- a/accessible/xpcom/xpcAccessibleMacInterface.mm +++ b/accessible/xpcom/xpcAccessibleMacInterface.mm @@ -24,27 +24,32 @@ using namespace mozilla::a11y; // xpcAccessibleMacNSObjectWrapper -NS_IMPL_ISUPPORTS(xpcAccessibleMacNSObjectWrapper, nsIAccessibleMacNSObjectWrapper) +NS_IMPL_ISUPPORTS(xpcAccessibleMacNSObjectWrapper, + nsIAccessibleMacNSObjectWrapper) xpcAccessibleMacNSObjectWrapper::xpcAccessibleMacNSObjectWrapper(id aNativeObj) : mNativeObject(aNativeObj) { [mNativeObject retain]; } -xpcAccessibleMacNSObjectWrapper::~xpcAccessibleMacNSObjectWrapper() { [mNativeObject release]; } +xpcAccessibleMacNSObjectWrapper::~xpcAccessibleMacNSObjectWrapper() { + [mNativeObject release]; +} id xpcAccessibleMacNSObjectWrapper::GetNativeObject() { return mNativeObject; } // xpcAccessibleMacInterface -NS_IMPL_ISUPPORTS_INHERITED(xpcAccessibleMacInterface, xpcAccessibleMacNSObjectWrapper, +NS_IMPL_ISUPPORTS_INHERITED(xpcAccessibleMacInterface, + xpcAccessibleMacNSObjectWrapper, nsIAccessibleMacInterface) xpcAccessibleMacInterface::xpcAccessibleMacInterface(Accessible* aObj) : xpcAccessibleMacNSObjectWrapper(GetNativeFromGeckoAccessible(aObj)) {} NS_IMETHODIMP -xpcAccessibleMacInterface::GetAttributeNames(nsTArray& aAttributeNames) { +xpcAccessibleMacInterface::GetAttributeNames( + nsTArray& aAttributeNames) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN if (!mNativeObject || [mNativeObject isExpired]) { @@ -63,14 +68,16 @@ xpcAccessibleMacInterface::GetAttributeNames(nsTArray& aAttributeNames } NS_IMETHODIMP -xpcAccessibleMacInterface::GetParameterizedAttributeNames(nsTArray& aAttributeNames) { +xpcAccessibleMacInterface::GetParameterizedAttributeNames( + nsTArray& aAttributeNames) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN if (!mNativeObject || [mNativeObject isExpired]) { return NS_ERROR_NOT_AVAILABLE; } - for (NSString* name in [mNativeObject accessibilityParameterizedAttributeNames]) { + for (NSString* name in + [mNativeObject accessibilityParameterizedAttributeNames]) { nsAutoString attribName; nsCocoaUtils::GetStringForNSString(name, attribName); aAttributeNames.AppendElement(attribName); @@ -117,7 +124,8 @@ xpcAccessibleMacInterface::PerformAction(const nsAString& aActionName) { } NS_IMETHODIMP -xpcAccessibleMacInterface::GetAttributeValue(const nsAString& aAttributeName, JSContext* aCx, +xpcAccessibleMacInterface::GetAttributeValue(const nsAString& aAttributeName, + JSContext* aCx, JS::MutableHandleValue aResult) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN @@ -126,17 +134,20 @@ xpcAccessibleMacInterface::GetAttributeValue(const nsAString& aAttributeName, JS } NSString* attribName = nsCocoaUtils::ToNSString(aAttributeName); - return NSObjectToJsValue([mNativeObject accessibilityAttributeValue:attribName], aCx, aResult); + return NSObjectToJsValue( + [mNativeObject accessibilityAttributeValue:attribName], aCx, aResult); NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE) } NS_IMETHODIMP -xpcAccessibleMacInterface::IsAttributeSettable(const nsAString& aAttributeName, bool* aIsSettable) { +xpcAccessibleMacInterface::IsAttributeSettable(const nsAString& aAttributeName, + bool* aIsSettable) { NS_ENSURE_ARG_POINTER(aIsSettable); NSString* attribName = nsCocoaUtils::ToNSString(aAttributeName); - if ([mNativeObject respondsToSelector:@selector(accessibilityIsAttributeSettable:)]) { + if ([mNativeObject + respondsToSelector:@selector(accessibilityIsAttributeSettable:)]) { *aIsSettable = [mNativeObject accessibilityIsAttributeSettable:attribName]; return NS_OK; } @@ -146,13 +157,15 @@ xpcAccessibleMacInterface::IsAttributeSettable(const nsAString& aAttributeName, NS_IMETHODIMP xpcAccessibleMacInterface::SetAttributeValue(const nsAString& aAttributeName, - JS::HandleValue aAttributeValue, JSContext* aCx) { + JS::HandleValue aAttributeValue, + JSContext* aCx) { nsresult rv = NS_OK; id obj = JsValueToNSObject(aAttributeValue, aCx, &rv); NS_ENSURE_SUCCESS(rv, rv); NSString* attribName = nsCocoaUtils::ToNSString(aAttributeName); - if ([mNativeObject respondsToSelector:@selector(accessibilitySetValue:forAttribute:)]) { + if ([mNativeObject respondsToSelector:@selector(accessibilitySetValue: + forAttribute:)]) { // The NSObject has an attribute setter, call that. [mNativeObject accessibilitySetValue:obj forAttribute:attribName]; return NS_OK; @@ -162,29 +175,30 @@ xpcAccessibleMacInterface::SetAttributeValue(const nsAString& aAttributeName, } NS_IMETHODIMP -xpcAccessibleMacInterface::GetParameterizedAttributeValue(const nsAString& aAttributeName, - JS::HandleValue aParameter, - JSContext* aCx, - JS::MutableHandleValue aResult) { +xpcAccessibleMacInterface::GetParameterizedAttributeValue( + const nsAString& aAttributeName, JS::HandleValue aParameter, JSContext* aCx, + JS::MutableHandleValue aResult) { nsresult rv = NS_OK; id paramObj = JsValueToNSObject(aParameter, aCx, &rv); NS_ENSURE_SUCCESS(rv, rv); NSString* attribName = nsCocoaUtils::ToNSString(aAttributeName); - return NSObjectToJsValue( - [mNativeObject accessibilityAttributeValue:attribName forParameter:paramObj], aCx, aResult); + return NSObjectToJsValue([mNativeObject accessibilityAttributeValue:attribName + forParameter:paramObj], + aCx, aResult); } bool xpcAccessibleMacInterface::SupportsSelector(SEL aSelector) { // return true if we have this selector, and if isAccessibilitySelectorAllowed // is implemented too whether it is "allowed". return [mNativeObject respondsToSelector:aSelector] && - (![mNativeObject respondsToSelector:@selector(isAccessibilitySelectorAllowed:selector:)] || + (![mNativeObject respondsToSelector:@selector + (isAccessibilitySelectorAllowed:selector:)] || [mNativeObject isAccessibilitySelectorAllowed:aSelector]); } -nsresult xpcAccessibleMacInterface::NSObjectToJsValue(id aObj, JSContext* aCx, - JS::MutableHandleValue aResult) { +nsresult xpcAccessibleMacInterface::NSObjectToJsValue( + id aObj, JSContext* aCx, JS::MutableHandleValue aResult) { if (!aObj) { aResult.set(JS::NullValue()); } else if ([aObj isKindOfClass:[NSString class]]) { @@ -201,7 +215,8 @@ nsresult xpcAccessibleMacInterface::NSObjectToJsValue(id aObj, JSContext* aCx, return NS_ERROR_FAILURE; } } else { - if (!mozilla::dom::ToJSValue(aCx, [(NSNumber*)aObj doubleValue], aResult)) { + if (!mozilla::dom::ToJSValue(aCx, [(NSNumber*)aObj doubleValue], + aResult)) { return NS_ERROR_FAILURE; } } @@ -209,18 +224,25 @@ nsresult xpcAccessibleMacInterface::NSObjectToJsValue(id aObj, JSContext* aCx, strcmp([(NSValue*)aObj objCType], @encode(NSPoint)) == 0) { NSPoint point = [(NSValue*)aObj pointValue]; return NSObjectToJsValue( - @[ [NSNumber numberWithDouble:point.x], [NSNumber numberWithDouble:point.y] ], aCx, - aResult); + @[ + [NSNumber numberWithDouble:point.x], + [NSNumber numberWithDouble:point.y] + ], + aCx, aResult); } else if ([aObj isKindOfClass:[NSValue class]] && strcmp([(NSValue*)aObj objCType], @encode(NSSize)) == 0) { NSSize size = [(NSValue*)aObj sizeValue]; return NSObjectToJsValue( - @[ [NSNumber numberWithDouble:size.width], [NSNumber numberWithDouble:size.height] ], aCx, - aResult); + @[ + [NSNumber numberWithDouble:size.width], + [NSNumber numberWithDouble:size.height] + ], + aCx, aResult); } else if ([aObj isKindOfClass:[NSValue class]] && strcmp([(NSValue*)aObj objCType], @encode(NSRange)) == 0) { NSRange range = [(NSValue*)aObj rangeValue]; - return NSObjectToJsValue(@[ @(range.location), @(range.length) ], aCx, aResult); + return NSObjectToJsValue(@[ @(range.location), @(range.length) ], aCx, + aResult); } else if ([aObj isKindOfClass:[NSValue class]] && strcmp([(NSValue*)aObj objCType], @encode(NSRect)) == 0) { NSRect rect = [(NSValue*)aObj rectValue]; @@ -263,14 +285,18 @@ nsresult xpcAccessibleMacInterface::NSObjectToJsValue(id aObj, JSContext* aCx, [attrStr enumerateAttributesInRange:NSMakeRange(0, [attrStr length]) - options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired - usingBlock:^(NSDictionary* attributes, NSRange range, BOOL* stop) { - NSString* str = [[attrStr string] substringWithRange:range]; + options: + NSAttributedStringEnumerationLongestEffectiveRangeNotRequired + usingBlock:^(NSDictionary* attributes, NSRange range, + BOOL* stop) { + NSString* str = + [[attrStr string] substringWithRange:range]; if (!str || !attributes) { return; } - NSMutableDictionary* attrRun = [attributes mutableCopy]; + NSMutableDictionary* attrRun = + [attributes mutableCopy]; attrRun[@"string"] = str; [attrRunArray addObject:attrRun]; @@ -282,28 +308,34 @@ nsresult xpcAccessibleMacInterface::NSObjectToJsValue(id aObj, JSContext* aCx, return NSObjectToJsValue(attrRunArray, aCx, aResult); } else if (CFGetTypeID(aObj) == CGColorGetTypeID()) { const CGFloat* components = CGColorGetComponents((CGColorRef)aObj); - NSString* hexString = - [NSString stringWithFormat:@"#%02x%02x%02x", (int)(components[0] * 0xff), - (int)(components[1] * 0xff), (int)(components[2] * 0xff)]; + NSString* hexString = [NSString + stringWithFormat:@"#%02x%02x%02x", (int)(components[0] * 0xff), + (int)(components[1] * 0xff), + (int)(components[2] * 0xff)]; return NSObjectToJsValue(hexString, aCx, aResult); } else if ([aObj respondsToSelector:@selector(isAccessibilityElement)]) { - // We expect all of our accessibility objects to implement isAccessibilityElement - // at the very least. If it is implemented we will assume its an accessibility object. - nsCOMPtr obj = new xpcAccessibleMacInterface(aObj); - return nsContentUtils::WrapNative(aCx, obj, &NS_GET_IID(nsIAccessibleMacInterface), aResult); + // We expect all of our accessibility objects to implement + // isAccessibilityElement at the very least. If it is implemented we will + // assume its an accessibility object. + nsCOMPtr obj = + new xpcAccessibleMacInterface(aObj); + return nsContentUtils::WrapNative( + aCx, obj, &NS_GET_IID(nsIAccessibleMacInterface), aResult); } else { // If this is any other kind of NSObject, just wrap it and return it. // It will be opaque and immutable on the JS side, but it can be // brought back to us in an argument. - nsCOMPtr obj = new xpcAccessibleMacNSObjectWrapper(aObj); - return nsContentUtils::WrapNative(aCx, obj, &NS_GET_IID(nsIAccessibleMacNSObjectWrapper), - aResult); + nsCOMPtr obj = + new xpcAccessibleMacNSObjectWrapper(aObj); + return nsContentUtils::WrapNative( + aCx, obj, &NS_GET_IID(nsIAccessibleMacNSObjectWrapper), aResult); } return NS_OK; } -id xpcAccessibleMacInterface::JsValueToNSObject(JS::HandleValue aValue, JSContext* aCx, +id xpcAccessibleMacInterface::JsValueToNSObject(JS::HandleValue aValue, + JSContext* aCx, nsresult* aResult) { *aResult = NS_OK; if (aValue.isInt32()) { @@ -363,9 +395,11 @@ id xpcAccessibleMacInterface::JsValueToNSObject(JS::HandleValue aValue, JSContex nsCOMPtr xpc = nsIXPConnect::XPConnect(); nsCOMPtr wrappedObj; - nsresult rv = xpc->GetWrappedNativeOfJSObject(aCx, obj, getter_AddRefs(wrappedObj)); + nsresult rv = + xpc->GetWrappedNativeOfJSObject(aCx, obj, getter_AddRefs(wrappedObj)); NS_ENSURE_SUCCESS(rv, nil); - nsCOMPtr macObjIface = do_QueryInterface(wrappedObj->Native()); + nsCOMPtr macObjIface = + do_QueryInterface(wrappedObj->Native()); return macObjIface->GetNativeObject(); } @@ -373,7 +407,8 @@ id xpcAccessibleMacInterface::JsValueToNSObject(JS::HandleValue aValue, JSContex return nil; } -id xpcAccessibleMacInterface::JsValueToNSValue(JS::HandleObject aObject, JSContext* aCx, +id xpcAccessibleMacInterface::JsValueToNSValue(JS::HandleObject aObject, + JSContext* aCx, nsresult* aResult) { *aResult = NS_ERROR_FAILURE; JS::RootedValue valueTypeValue(aCx); @@ -421,14 +456,15 @@ id xpcAccessibleMacInterface::JsValueToNSValue(JS::HandleObject aObject, JSConte } *aResult = NS_OK; - return [NSValue valueWithRange:NSMakeRange(locationValue.toInt32(), lengthValue.toInt32())]; + return [NSValue valueWithRange:NSMakeRange(locationValue.toInt32(), + lengthValue.toInt32())]; } return nil; } -id xpcAccessibleMacInterface::JsValueToSpecifiedNSObject(JS::HandleObject aObject, JSContext* aCx, - nsresult* aResult) { +id xpcAccessibleMacInterface::JsValueToSpecifiedNSObject( + JS::HandleObject aObject, JSContext* aCx, nsresult* aResult) { *aResult = NS_ERROR_FAILURE; JS::RootedValue objectTypeValue(aCx); if (!JS_GetProperty(aCx, aObject, "objectType", &objectTypeValue)) { @@ -509,7 +545,8 @@ xpcAccessibleMacEvent::~xpcAccessibleMacEvent() { NS_IMETHODIMP xpcAccessibleMacEvent::GetMacIface(nsIAccessibleMacInterface** aMacIface) { - RefPtr macIface = new xpcAccessibleMacInterface(mNativeObject); + RefPtr macIface = + new xpcAccessibleMacInterface(mNativeObject); macIface.forget(aMacIface); return NS_OK; } @@ -519,20 +556,25 @@ xpcAccessibleMacEvent::GetData(JSContext* aCx, JS::MutableHandleValue aData) { return xpcAccessibleMacInterface::NSObjectToJsValue(mData, aCx, aData); } -void xpcAccessibleMacEvent::FireEvent(id aNativeObj, id aNotification, id aUserInfo) { - if (nsCOMPtr obsService = services::GetObserverService()) { +void xpcAccessibleMacEvent::FireEvent(id aNativeObj, id aNotification, + id aUserInfo) { + if (nsCOMPtr obsService = + services::GetObserverService()) { nsCOMPtr observers; // Get all observers for the mac event topic. - obsService->EnumerateObservers(NS_ACCESSIBLE_MAC_EVENT_TOPIC, getter_AddRefs(observers)); + obsService->EnumerateObservers(NS_ACCESSIBLE_MAC_EVENT_TOPIC, + getter_AddRefs(observers)); if (observers) { bool hasObservers = false; observers->HasMoreElements(&hasObservers); // If we have observers, notify them. if (hasObservers) { - nsCOMPtr xpcIface = new xpcAccessibleMacEvent(aNativeObj, aUserInfo); + nsCOMPtr xpcIface = + new xpcAccessibleMacEvent(aNativeObj, aUserInfo); nsAutoString notificationStr; nsCocoaUtils::GetStringForNSString(aNotification, notificationStr); - obsService->NotifyObservers(xpcIface, NS_ACCESSIBLE_MAC_EVENT_TOPIC, notificationStr.get()); + obsService->NotifyObservers(xpcIface, NS_ACCESSIBLE_MAC_EVENT_TOPIC, + notificationStr.get()); } } } diff --git a/browser/components/migration/nsKeychainMigrationUtils.mm b/browser/components/migration/nsKeychainMigrationUtils.mm index 3b0f662914cd..85c09c9ef37b 100644 --- a/browser/components/migration/nsKeychainMigrationUtils.mm +++ b/browser/components/migration/nsKeychainMigrationUtils.mm @@ -19,7 +19,8 @@ NS_IMPL_ISUPPORTS(nsKeychainMigrationUtils, nsIKeychainMigrationUtils) NS_IMETHODIMP nsKeychainMigrationUtils::GetGenericPassword(const nsACString& aServiceName, - const nsACString& aAccountName, nsACString& aKey) { + const nsACString& aAccountName, + nsACString& aKey) { // To retrieve a secret, we create a CFDictionary of the form: // { class: generic password, // service: the given service name @@ -31,9 +32,12 @@ nsKeychainMigrationUtils::GetGenericPassword(const nsACString& aServiceName, // matching the given service and account names. We then extract the data // (i.e. the secret) and return it. NSDictionary* searchDictionary = @{ - (__bridge NSString*)kSecClass : (__bridge NSString*)kSecClassGenericPassword, - (__bridge NSString*)kSecAttrService : nsCocoaUtils::ToNSString(aServiceName), - (__bridge NSString*)kSecAttrAccount : nsCocoaUtils::ToNSString(aAccountName), + (__bridge NSString*) + kSecClass : (__bridge NSString*)kSecClassGenericPassword, + (__bridge NSString*) + kSecAttrService : nsCocoaUtils::ToNSString(aServiceName), + (__bridge NSString*) + kSecAttrAccount : nsCocoaUtils::ToNSString(aAccountName), (__bridge NSString*)kSecMatchLimit : (__bridge NSString*)kSecMatchLimitOne, (__bridge NSString*)kSecReturnAttributes : @YES, (__bridge NSString*)kSecReturnData : @YES @@ -41,9 +45,11 @@ nsKeychainMigrationUtils::GetGenericPassword(const nsACString& aServiceName, CFTypeRef item; // https://developer.apple.com/documentation/security/1398306-secitemcopymatching - OSStatus rv = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, &item); + OSStatus rv = + SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, &item); if (rv != errSecSuccess) { - MOZ_LOG(gKeychainUtilsLog, LogLevel::Debug, ("SecItemCopyMatching failed: %d", rv)); + MOZ_LOG(gKeychainUtilsLog, LogLevel::Debug, + ("SecItemCopyMatching failed: %d", rv)); return NS_ERROR_FAILURE; } NSDictionary* resultDict = [(__bridge NSDictionary*)item autorelease]; @@ -53,8 +59,8 @@ nsKeychainMigrationUtils::GetGenericPassword(const nsACString& aServiceName, return NS_ERROR_FAILURE; } if ([secret length] != 0) { - // We assume that the data is UTF-8 encoded since that seems to be common and - // Keychain Access shows it with that encoding. + // We assume that the data is UTF-8 encoded since that seems to be common + // and Keychain Access shows it with that encoding. aKey.Assign(reinterpret_cast([secret bytes]), [secret length]); } diff --git a/dom/media/mediacontrol/tests/gtest/TestMediaKeysEventMac.mm b/dom/media/mediacontrol/tests/gtest/TestMediaKeysEventMac.mm index 3c8ce8cd9e85..05cd12946812 100644 --- a/dom/media/mediacontrol/tests/gtest/TestMediaKeysEventMac.mm +++ b/dom/media/mediacontrol/tests/gtest/TestMediaKeysEventMac.mm @@ -18,27 +18,31 @@ using namespace mozilla::widget; static const int kSystemDefinedEventMediaKeysSubtype = 8; -static void SendFakeEvent(RefPtr& aSource, int aKeyData) { - NSEvent* event = [NSEvent otherEventWithType:NSEventTypeSystemDefined - location:NSZeroPoint - modifierFlags:0 - timestamp:0 - windowNumber:0 - context:nil - subtype:kSystemDefinedEventMediaKeysSubtype - data1:aKeyData - data2:0]; - aSource->EventTapCallback(nullptr, static_cast(0), [event CGEvent], aSource.get()); +static void SendFakeEvent(RefPtr& aSource, + int aKeyData) { + NSEvent* event = + [NSEvent otherEventWithType:NSEventTypeSystemDefined + location:NSZeroPoint + modifierFlags:0 + timestamp:0 + windowNumber:0 + context:nil + subtype:kSystemDefinedEventMediaKeysSubtype + data1:aKeyData + data2:0]; + aSource->EventTapCallback(nullptr, static_cast(0), + [event CGEvent], aSource.get()); } -static void NotifyFakeNonMediaKey(RefPtr& aSource, - bool aIsKeyPressed) { +static void NotifyFakeNonMediaKey( + RefPtr& aSource, bool aIsKeyPressed) { int keyData = 0 | ((aIsKeyPressed ? 0xA : 0xB) << 8); SendFakeEvent(aSource, keyData); } -static void NotifyFakeMediaControlKey(RefPtr& aSource, - MediaControlKey aEvent, bool aIsKeyPressed) { +static void NotifyFakeMediaControlKey( + RefPtr& aSource, MediaControlKey aEvent, + bool aIsKeyPressed) { int keyData = 0; if (aEvent == MediaControlKey::Playpause) { keyData = NX_KEYTYPE_PLAY << 16; @@ -51,27 +55,30 @@ static void NotifyFakeMediaControlKey(RefPtr& a SendFakeEvent(aSource, keyData); } -static void NotifyKeyPressedMediaKey(RefPtr& aSource, - MediaControlKey aEvent) { +static void NotifyKeyPressedMediaKey( + RefPtr& aSource, MediaControlKey aEvent) { NotifyFakeMediaControlKey(aSource, aEvent, true /* key pressed */); } -static void NotifyKeyReleasedMediaKeysEvent(RefPtr& aSource, - MediaControlKey aEvent) { +static void NotifyKeyReleasedMediaKeysEvent( + RefPtr& aSource, MediaControlKey aEvent) { NotifyFakeMediaControlKey(aSource, aEvent, false /* key released */); } -static void NotifyKeyPressedNonMediaKeysEvents(RefPtr& aSource) { +static void NotifyKeyPressedNonMediaKeysEvents( + RefPtr& aSource) { NotifyFakeNonMediaKey(aSource, true /* key pressed */); } -static void NotifyKeyReleasedNonMediaKeysEvents(RefPtr& aSource) { +static void NotifyKeyReleasedNonMediaKeysEvents( + RefPtr& aSource) { NotifyFakeNonMediaKey(aSource, false /* key released */); } TEST(MediaHardwareKeysEventSourceMac, TestKeyPressedMediaKeysEvent) { - RefPtr source = new MediaHardwareKeysEventSourceMac(); + RefPtr source = + new MediaHardwareKeysEventSourceMac(); ASSERT_TRUE(source->GetListenersNum() == 0); RefPtr listener = new MediaKeyListenerTest(); @@ -94,7 +101,8 @@ TEST(MediaHardwareKeysEventSourceMac, TestKeyPressedMediaKeysEvent) TEST(MediaHardwareKeysEventSourceMac, TestKeyReleasedMediaKeysEvent) { - RefPtr source = new MediaHardwareKeysEventSourceMac(); + RefPtr source = + new MediaHardwareKeysEventSourceMac(); ASSERT_TRUE(source->GetListenersNum() == 0); RefPtr listener = new MediaKeyListenerTest(); @@ -117,7 +125,8 @@ TEST(MediaHardwareKeysEventSourceMac, TestKeyReleasedMediaKeysEvent) TEST(MediaHardwareKeysEventSourceMac, TestNonMediaKeysEvent) { - RefPtr source = new MediaHardwareKeysEventSourceMac(); + RefPtr source = + new MediaHardwareKeysEventSourceMac(); ASSERT_TRUE(source->GetListenersNum() == 0); RefPtr listener = new MediaKeyListenerTest(); diff --git a/dom/media/mediacontrol/tests/gtest/TestMediaKeysEventMediaCenter.mm b/dom/media/mediacontrol/tests/gtest/TestMediaKeysEventMediaCenter.mm index 19cdba2cf371..fd439006bcaa 100644 --- a/dom/media/mediacontrol/tests/gtest/TestMediaKeysEventMediaCenter.mm +++ b/dom/media/mediacontrol/tests/gtest/TestMediaKeysEventMediaCenter.mm @@ -123,7 +123,8 @@ TEST(MediaHardwareKeysEventSourceMacMediaCenter, TestMediaCenterPrevNextEvent) ASSERT_TRUE(listener->IsResultEqualTo(MediaControlKey::Nexttrack)); - MediaCenterEventHandler previousHandler = source->CreatePreviousTrackHandler(); + MediaCenterEventHandler previousHandler = + source->CreatePreviousTrackHandler(); previousHandler(nil); @@ -153,9 +154,12 @@ TEST(MediaHardwareKeysEventSourceMacMediaCenter, TestSetMetadata) // before checking the result. PR_Sleep(PR_SecondsToInterval(1)); MPNowPlayingInfoCenter* center = [MPNowPlayingInfoCenter defaultCenter]; - ASSERT_TRUE([center.nowPlayingInfo[MPMediaItemPropertyTitle] isEqualToString:@"MediaPlayback"]); - ASSERT_TRUE([center.nowPlayingInfo[MPMediaItemPropertyArtist] isEqualToString:@"Firefox"]); - ASSERT_TRUE([center.nowPlayingInfo[MPMediaItemPropertyAlbumTitle] isEqualToString:@"Mozilla"]); + ASSERT_TRUE([center.nowPlayingInfo[MPMediaItemPropertyTitle] + isEqualToString:@"MediaPlayback"]); + ASSERT_TRUE([center.nowPlayingInfo[MPMediaItemPropertyArtist] + isEqualToString:@"Firefox"]); + ASSERT_TRUE([center.nowPlayingInfo[MPMediaItemPropertyAlbumTitle] + isEqualToString:@"Mozilla"]); source->Close(); PR_Sleep(PR_SecondsToInterval(1)); diff --git a/dom/media/systemservices/objc_video_capture/device_info.mm b/dom/media/systemservices/objc_video_capture/device_info.mm index d0299a9ec9c1..4f82e600947f 100644 --- a/dom/media/systemservices/objc_video_capture/device_info.mm +++ b/dom/media/systemservices/objc_video_capture/device_info.mm @@ -28,11 +28,13 @@ using namespace webrtc; using namespace videocapturemodule; static NSArray* camera_presets = @[ - AVCaptureSessionPreset352x288, AVCaptureSessionPreset640x480, AVCaptureSessionPreset1280x720 + AVCaptureSessionPreset352x288, AVCaptureSessionPreset640x480, + AVCaptureSessionPreset1280x720 ]; -#define IOS_UNSUPPORTED() \ - RTC_LOG(LS_ERROR) << __FUNCTION__ << " is not supported on the iOS platform."; \ +#define IOS_UNSUPPORTED() \ + RTC_LOG(LS_ERROR) << __FUNCTION__ \ + << " is not supported on the iOS platform."; \ return -1; VideoCaptureModule::DeviceInfo* VideoCaptureImpl::CreateDeviceInfo() { @@ -60,7 +62,8 @@ int32_t DeviceInfoIos::Init() { for (NSString* preset in camera_presets) { BOOL support = [avDevice supportsAVCaptureSessionPreset:preset]; if (support) { - VideoCaptureCapability capability = [DeviceInfoIosObjC capabilityForPreset:preset]; + VideoCaptureCapability capability = + [DeviceInfoIosObjC capabilityForPreset:preset]; capabilityVector.push_back(capability); } } @@ -73,31 +76,36 @@ int32_t DeviceInfoIos::Init() { } std::string deviceIdCopy(deviceId); std::pair mapPair = - std::pair(deviceIdCopy, capabilityVector); + std::pair(deviceIdCopy, + capabilityVector); _capabilitiesMap.insert(mapPair); } return 0; } -uint32_t DeviceInfoIos::NumberOfDevices() { return [DeviceInfoIosObjC captureDeviceCount]; } +uint32_t DeviceInfoIos::NumberOfDevices() { + return [DeviceInfoIosObjC captureDeviceCount]; +} -int32_t DeviceInfoIos::GetDeviceName(uint32_t deviceNumber, char* deviceNameUTF8, - uint32_t deviceNameUTF8Length, char* deviceUniqueIdUTF8, - uint32_t deviceUniqueIdUTF8Length, char* productUniqueIdUTF8, - uint32_t productUniqueIdUTF8Length, pid_t* pid) { +int32_t DeviceInfoIos::GetDeviceName( + uint32_t deviceNumber, char* deviceNameUTF8, uint32_t deviceNameUTF8Length, + char* deviceUniqueIdUTF8, uint32_t deviceUniqueIdUTF8Length, + char* productUniqueIdUTF8, uint32_t productUniqueIdUTF8Length, pid_t* pid) { if (deviceNumber >= NumberOfDevices()) { return -1; } NSString* deviceName = [DeviceInfoIosObjC deviceNameForIndex:deviceNumber]; - NSString* deviceUniqueId = [DeviceInfoIosObjC deviceUniqueIdForIndex:deviceNumber]; + NSString* deviceUniqueId = + [DeviceInfoIosObjC deviceUniqueIdForIndex:deviceNumber]; strncpy(deviceNameUTF8, [deviceName UTF8String], deviceNameUTF8Length); deviceNameUTF8[deviceNameUTF8Length - 1] = '\0'; - strncpy(deviceUniqueIdUTF8, deviceUniqueId.UTF8String, deviceUniqueIdUTF8Length); + strncpy(deviceUniqueIdUTF8, deviceUniqueId.UTF8String, + deviceUniqueIdUTF8Length); deviceUniqueIdUTF8[deviceUniqueIdUTF8Length - 1] = '\0'; if (productUniqueIdUTF8) { @@ -140,14 +148,14 @@ int32_t DeviceInfoIos::GetCapability(const char* deviceUniqueIdUTF8, return -1; } -int32_t DeviceInfoIos::DisplayCaptureSettingsDialogBox(const char* deviceUniqueIdUTF8, - const char* dialogTitleUTF8, - void* parentWindow, uint32_t positionX, - uint32_t positionY) { +int32_t DeviceInfoIos::DisplayCaptureSettingsDialogBox( + const char* deviceUniqueIdUTF8, const char* dialogTitleUTF8, + void* parentWindow, uint32_t positionX, uint32_t positionY) { IOS_UNSUPPORTED(); } -int32_t DeviceInfoIos::GetOrientation(const char* deviceUniqueIdUTF8, VideoRotation& orientation) { +int32_t DeviceInfoIos::GetOrientation(const char* deviceUniqueIdUTF8, + VideoRotation& orientation) { if (strcmp(deviceUniqueIdUTF8, "Front Camera") == 0) { orientation = kVideoRotation_0; } else { diff --git a/dom/media/systemservices/objc_video_capture/device_info_avfoundation.mm b/dom/media/systemservices/objc_video_capture/device_info_avfoundation.mm index fae65ff34374..f731b85e2afe 100644 --- a/dom/media/systemservices/objc_video_capture/device_info_avfoundation.mm +++ b/dom/media/systemservices/objc_video_capture/device_info_avfoundation.mm @@ -17,12 +17,14 @@ namespace webrtc::videocapturemodule { /* static */ -int32_t DeviceInfoAvFoundation::ConvertAVFrameRateToCapabilityFPS(Float64 aRate) { +int32_t DeviceInfoAvFoundation::ConvertAVFrameRateToCapabilityFPS( + Float64 aRate) { return static_cast(aRate); } /* static */ -webrtc::VideoType DeviceInfoAvFoundation::ConvertFourCCToVideoType(FourCharCode aCode) { +webrtc::VideoType DeviceInfoAvFoundation::ConvertFourCCToVideoType( + FourCharCode aCode) { switch (aCode) { case kCVPixelFormatType_420YpCbCr8Planar: case kCVPixelFormatType_420YpCbCr8PlanarFullRange: @@ -57,11 +59,14 @@ webrtc::VideoType DeviceInfoAvFoundation::ConvertFourCCToVideoType(FourCharCode } DeviceInfoAvFoundation::DeviceInfoAvFoundation() - : mInvalidateCapabilities(false), mDeviceChangeCaptureInfo([[DeviceInfoIosObjC alloc] init]) { + : mInvalidateCapabilities(false), + mDeviceChangeCaptureInfo([[DeviceInfoIosObjC alloc] init]) { [mDeviceChangeCaptureInfo registerOwner:this]; } -DeviceInfoAvFoundation::~DeviceInfoAvFoundation() { [mDeviceChangeCaptureInfo registerOwner:nil]; } +DeviceInfoAvFoundation::~DeviceInfoAvFoundation() { + [mDeviceChangeCaptureInfo registerOwner:nil]; +} void DeviceInfoAvFoundation::DeviceChange() { mInvalidateCapabilities = true; @@ -74,12 +79,11 @@ uint32_t DeviceInfoAvFoundation::NumberOfDevices() { return mDevicesAndCapabilities.size(); } -int32_t DeviceInfoAvFoundation::GetDeviceName(uint32_t aDeviceNumber, char* aDeviceNameUTF8, - uint32_t aDeviceNameLength, char* aDeviceUniqueIdUTF8, - uint32_t aDeviceUniqueIdUTF8Length, - char* /* aProductUniqueIdUTF8 */, - uint32_t /* aProductUniqueIdUTF8Length */, - pid_t* /* aPid */) { +int32_t DeviceInfoAvFoundation::GetDeviceName( + uint32_t aDeviceNumber, char* aDeviceNameUTF8, uint32_t aDeviceNameLength, + char* aDeviceUniqueIdUTF8, uint32_t aDeviceUniqueIdUTF8Length, + char* /* aProductUniqueIdUTF8 */, uint32_t /* aProductUniqueIdUTF8Length */, + pid_t* /* aPid */) { RTC_DCHECK_RUN_ON(&mChecker); // Don't EnsureCapabilitiesMap() here, since: // 1) That might invalidate the capabilities map @@ -100,7 +104,8 @@ int32_t DeviceInfoAvFoundation::GetDeviceName(uint32_t aDeviceNumber, char* aDev return 0; } -int32_t DeviceInfoAvFoundation::NumberOfCapabilities(const char* aDeviceUniqueIdUTF8) { +int32_t DeviceInfoAvFoundation::NumberOfCapabilities( + const char* aDeviceUniqueIdUTF8) { RTC_DCHECK_RUN_ON(&mChecker); std::string deviceUniqueId(aDeviceUniqueIdUTF8); @@ -113,9 +118,9 @@ int32_t DeviceInfoAvFoundation::NumberOfCapabilities(const char* aDeviceUniqueId return static_cast(capabilities.size()); } -int32_t DeviceInfoAvFoundation::GetCapability(const char* aDeviceUniqueIdUTF8, - const uint32_t aDeviceCapabilityNumber, - VideoCaptureCapability& aCapability) { +int32_t DeviceInfoAvFoundation::GetCapability( + const char* aDeviceUniqueIdUTF8, const uint32_t aDeviceCapabilityNumber, + VideoCaptureCapability& aCapability) { RTC_DCHECK_RUN_ON(&mChecker); std::string deviceUniqueId(aDeviceUniqueIdUTF8); @@ -133,7 +138,8 @@ int32_t DeviceInfoAvFoundation::GetCapability(const char* aDeviceUniqueIdUTF8, return 0; } -int32_t DeviceInfoAvFoundation::CreateCapabilityMap(const char* aDeviceUniqueIdUTF8) { +int32_t DeviceInfoAvFoundation::CreateCapabilityMap( + const char* aDeviceUniqueIdUTF8) { RTC_DCHECK_RUN_ON(&mChecker); const size_t deviceUniqueIdUTF8Length = strlen(aDeviceUniqueIdUTF8); @@ -141,7 +147,8 @@ int32_t DeviceInfoAvFoundation::CreateCapabilityMap(const char* aDeviceUniqueIdU RTC_LOG(LS_INFO) << "Device name too long"; return -1; } - RTC_LOG(LS_INFO) << "CreateCapabilityMap called for device " << aDeviceUniqueIdUTF8; + RTC_LOG(LS_INFO) << "CreateCapabilityMap called for device " + << aDeviceUniqueIdUTF8; std::string deviceUniqueId(aDeviceUniqueIdUTF8); const auto* tup = FindDeviceAndCapabilities(deviceUniqueId); if (!tup) { @@ -151,16 +158,18 @@ int32_t DeviceInfoAvFoundation::CreateCapabilityMap(const char* aDeviceUniqueIdU // Store the new used device name _lastUsedDeviceNameLength = deviceUniqueIdUTF8Length; - _lastUsedDeviceName = - static_cast(realloc(_lastUsedDeviceName, _lastUsedDeviceNameLength + 1)); - memcpy(_lastUsedDeviceName, aDeviceUniqueIdUTF8, _lastUsedDeviceNameLength + 1); + _lastUsedDeviceName = static_cast( + realloc(_lastUsedDeviceName, _lastUsedDeviceNameLength + 1)); + memcpy(_lastUsedDeviceName, aDeviceUniqueIdUTF8, + _lastUsedDeviceNameLength + 1); const auto& [_, __, capabilities] = *tup; _captureCapabilities = capabilities; return static_cast(_captureCapabilities.size()); } -auto DeviceInfoAvFoundation::FindDeviceAndCapabilities(const std::string& aDeviceUniqueId) const +auto DeviceInfoAvFoundation::FindDeviceAndCapabilities( + const std::string& aDeviceUniqueId) const -> const std::tuple* { RTC_DCHECK_RUN_ON(&mChecker); for (const auto& tup : mDevicesAndCapabilities) { @@ -185,13 +194,14 @@ void DeviceInfoAvFoundation::EnsureCapabilitiesMap() { for (AVCaptureDevice* device in [RTCCameraVideoCapturer captureDevices]) { std::string uniqueId = [NSString stdStringForString:device.uniqueID]; std::string name = [NSString stdStringForString:device.localizedName]; - auto& [_, __, capabilities] = - mDevicesAndCapabilities.emplace_back(uniqueId, name, VideoCaptureCapabilities()); + auto& [_, __, capabilities] = mDevicesAndCapabilities.emplace_back( + uniqueId, name, VideoCaptureCapabilities()); for (AVCaptureDeviceFormat* format in [RTCCameraVideoCapturer supportedFormatsForDevice:device]) { VideoCaptureCapability cap; - FourCharCode fourcc = CMFormatDescriptionGetMediaSubType(format.formatDescription); + FourCharCode fourcc = + CMFormatDescriptionGetMediaSubType(format.formatDescription); cap.videoType = ConvertFourCCToVideoType(fourcc); CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription); diff --git a/dom/media/systemservices/objc_video_capture/device_info_objc.mm b/dom/media/systemservices/objc_video_capture/device_info_objc.mm index 6e9435daff66..048565e04cd9 100644 --- a/dom/media/systemservices/objc_video_capture/device_info_objc.mm +++ b/dom/media/systemservices/objc_video_capture/device_info_objc.mm @@ -34,7 +34,8 @@ if (!_owner && owner) { [self configureObservers]; } else if (_owner && !owner) { - NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter]; + NSNotificationCenter* notificationCenter = + [NSNotificationCenter defaultCenter]; for (id observer in _observers) { [notificationCenter removeObserver:observer]; } @@ -47,7 +48,8 @@ + (int)captureDeviceCount { int cnt = 0; @try { - for (AVCaptureDevice* device in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { + for (AVCaptureDevice* device in + [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { if ([device isSuspended]) { continue; } @@ -62,7 +64,8 @@ + (AVCaptureDevice*)captureDeviceForIndex:(int)index { int cnt = 0; @try { - for (AVCaptureDevice* device in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { + for (AVCaptureDevice* device in + [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { if ([device isSuspended]) { continue; } @@ -79,7 +82,8 @@ } + (AVCaptureDevice*)captureDeviceForUniqueId:(NSString*)uniqueId { - for (AVCaptureDevice* device in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { + for (AVCaptureDevice* device in + [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { if ([device isSuspended]) { continue; } @@ -133,34 +137,36 @@ - (void)configureObservers { // register device connected / disconnected event - NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter]; + NSNotificationCenter* notificationCenter = + [NSNotificationCenter defaultCenter]; - id deviceWasConnectedObserver = - [notificationCenter addObserverForName:AVCaptureDeviceWasConnectedNotification - object:nil - queue:[NSOperationQueue mainQueue] - usingBlock:^(NSNotification* note) { - [_lock lock]; - AVCaptureDevice* device = [note object]; - BOOL isVideoDevice = [device hasMediaType:AVMediaTypeVideo]; - if (isVideoDevice && _owner) _owner->DeviceChange(); - [_lock unlock]; - }]; + id deviceWasConnectedObserver = [notificationCenter + addObserverForName:AVCaptureDeviceWasConnectedNotification + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification* note) { + [_lock lock]; + AVCaptureDevice* device = [note object]; + BOOL isVideoDevice = [device hasMediaType:AVMediaTypeVideo]; + if (isVideoDevice && _owner) _owner->DeviceChange(); + [_lock unlock]; + }]; - id deviceWasDisconnectedObserver = - [notificationCenter addObserverForName:AVCaptureDeviceWasDisconnectedNotification - object:nil - queue:[NSOperationQueue mainQueue] - usingBlock:^(NSNotification* note) { - [_lock lock]; - AVCaptureDevice* device = [note object]; - BOOL isVideoDevice = [device hasMediaType:AVMediaTypeVideo]; - if (isVideoDevice && _owner) _owner->DeviceChange(); - [_lock unlock]; - }]; + id deviceWasDisconnectedObserver = [notificationCenter + addObserverForName:AVCaptureDeviceWasDisconnectedNotification + object:nil + queue:[NSOperationQueue mainQueue] + usingBlock:^(NSNotification* note) { + [_lock lock]; + AVCaptureDevice* device = [note object]; + BOOL isVideoDevice = [device hasMediaType:AVMediaTypeVideo]; + if (isVideoDevice && _owner) _owner->DeviceChange(); + [_lock unlock]; + }]; - _observers = [[NSArray alloc] - initWithObjects:deviceWasConnectedObserver, deviceWasDisconnectedObserver, nil]; + _observers = + [[NSArray alloc] initWithObjects:deviceWasConnectedObserver, + deviceWasDisconnectedObserver, nil]; } @end diff --git a/dom/media/systemservices/objc_video_capture/rtc_video_capture_objc.mm b/dom/media/systemservices/objc_video_capture/rtc_video_capture_objc.mm index 0a36768fa85c..7253ad1c73df 100644 --- a/dom/media/systemservices/objc_video_capture/rtc_video_capture_objc.mm +++ b/dom/media/systemservices/objc_video_capture/rtc_video_capture_objc.mm @@ -57,18 +57,22 @@ using namespace webrtc::videocapturemodule; } // create and configure a new output (using callbacks) - AVCaptureVideoDataOutput* captureOutput = [[AVCaptureVideoDataOutput alloc] init]; + AVCaptureVideoDataOutput* captureOutput = + [[AVCaptureVideoDataOutput alloc] init]; NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey; - NSNumber* val = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_422YpCbCr8]; - NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:val forKey:key]; + NSNumber* val = + [NSNumber numberWithUnsignedInt:kCVPixelFormatType_422YpCbCr8]; + NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:val + forKey:key]; captureOutput.videoSettings = videoSettings; // add new output if ([_captureSession canAddOutput:captureOutput]) { [_captureSession addOutput:captureOutput]; } else { - RTC_LOG(LS_ERROR) << __FUNCTION__ << ": Could not add output to AVCaptureSession"; + RTC_LOG(LS_ERROR) << __FUNCTION__ + << ": Could not add output to AVCaptureSession"; } #ifdef WEBRTC_IOS @@ -86,12 +90,14 @@ using namespace webrtc::videocapturemodule; #endif } - // Create a serial queue on which video capture will run. By setting the target, - // blocks should still run on DISPATH_QUEUE_PRIORITY_DEFAULT rather than creating - // a new thread. - _frameQueue = dispatch_queue_create("org.webrtc.videocapture", DISPATCH_QUEUE_SERIAL); - dispatch_set_target_queue(_frameQueue, - dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); + // Create a serial queue on which video capture will run. By setting the + // target, blocks should still run on DISPATH_QUEUE_PRIORITY_DEFAULT rather + // than creating a new thread. + _frameQueue = + dispatch_queue_create("org.webrtc.videocapture", DISPATCH_QUEUE_SERIAL); + dispatch_set_target_queue( + _frameQueue, + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); return self; } @@ -144,11 +150,13 @@ using namespace webrtc::videocapturemodule; if (capability.width > 1280 || capability.height > 720) { return NO; } - } else if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset640x480]) { + } else if ([_captureSession + canSetSessionPreset:AVCaptureSessionPreset640x480]) { if (capability.width > 640 || capability.height > 480) { return NO; } - } else if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset352x288]) { + } else if ([_captureSession + canSetSessionPreset:AVCaptureSessionPreset352x288]) { if (capability.width > 352 || capability.height > 288) { return NO; } @@ -175,8 +183,10 @@ using namespace webrtc::videocapturemodule; return [[_captureSession outputs] firstObject]; } -- (void)startCaptureInBackgroundWithOutput:(AVCaptureVideoDataOutput*)currentOutput { - NSString* captureQuality = [NSString stringWithString:AVCaptureSessionPresetLow]; +- (void)startCaptureInBackgroundWithOutput: + (AVCaptureVideoDataOutput*)currentOutput { + NSString* captureQuality = + [NSString stringWithString:AVCaptureSessionPresetLow]; if (_capability.width >= 1280 || _capability.height >= 720) { captureQuality = [NSString stringWithString:AVCaptureSessionPreset1280x720]; } else if (_capability.width >= 640 || _capability.height >= 480) { @@ -214,7 +224,8 @@ using namespace webrtc::videocapturemodule; _connection.videoOrientation = AVCaptureVideoOrientationPortrait; break; case UIDeviceOrientationPortraitUpsideDown: - _connection.videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown; + _connection.videoOrientation = + AVCaptureVideoOrientationPortraitUpsideDown; break; case UIDeviceOrientationLandscapeLeft: _connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight; @@ -236,7 +247,8 @@ using namespace webrtc::videocapturemodule; - (void)onVideoError:(NSNotification*)notification { NSLog(@"onVideoError: %@", notification); // TODO(sjlee): make the specific error handling with this notification. - RTC_LOG(LS_ERROR) << __FUNCTION__ << ": [AVCaptureSession startRunning] error."; + RTC_LOG(LS_ERROR) << __FUNCTION__ + << ": [AVCaptureSession startRunning] error."; } - (BOOL)stopCapture { @@ -265,7 +277,8 @@ using namespace webrtc::videocapturemodule; NSArray* currentInputs = [_captureSession inputs]; // remove current input if ([currentInputs count] > 0) { - AVCaptureInput* currentInput = (AVCaptureInput*)[currentInputs objectAtIndex:0]; + AVCaptureInput* currentInput = + (AVCaptureInput*)[currentInputs objectAtIndex:0]; [_captureSession removeInput:currentInput]; } @@ -277,7 +290,8 @@ using namespace webrtc::videocapturemodule; return NO; } - AVCaptureDevice* captureDevice = [DeviceInfoIosObjC captureDeviceForUniqueId:uniqueId]; + AVCaptureDevice* captureDevice = + [DeviceInfoIosObjC captureDeviceForUniqueId:uniqueId]; if (!captureDevice) { return NO; @@ -285,13 +299,15 @@ using namespace webrtc::videocapturemodule; // now create capture session input out of AVCaptureDevice NSError* deviceError = nil; - AVCaptureDeviceInput* newCaptureInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice - error:&deviceError]; + AVCaptureDeviceInput* newCaptureInput = + [AVCaptureDeviceInput deviceInputWithDevice:captureDevice + error:&deviceError]; if (!newCaptureInput) { const char* errorMessage = [[deviceError localizedDescription] UTF8String]; - RTC_LOG(LS_ERROR) << __FUNCTION__ << ": deviceInputWithDevice error:" << errorMessage; + RTC_LOG(LS_ERROR) << __FUNCTION__ + << ": deviceInputWithDevice error:" << errorMessage; return NO; } diff --git a/dom/media/systemservices/objc_video_capture/video_capture.mm b/dom/media/systemservices/objc_video_capture/video_capture.mm index 63aef3204cfe..9203f698750c 100644 --- a/dom/media/systemservices/objc_video_capture/video_capture.mm +++ b/dom/media/systemservices/objc_video_capture/video_capture.mm @@ -23,7 +23,8 @@ using namespace mozilla; using namespace webrtc; using namespace videocapturemodule; -rtc::scoped_refptr VideoCaptureImpl::Create(const char* deviceUniqueIdUTF8) { +rtc::scoped_refptr VideoCaptureImpl::Create( + const char* deviceUniqueIdUTF8) { if (StaticPrefs::media_getusermedia_camera_macavf_enabled_AtStartup()) { return VideoCaptureAvFoundation::Create(deviceUniqueIdUTF8); } @@ -44,12 +45,14 @@ VideoCaptureIos::~VideoCaptureIos() { } } -rtc::scoped_refptr VideoCaptureIos::Create(const char* deviceUniqueIdUTF8) { +rtc::scoped_refptr VideoCaptureIos::Create( + const char* deviceUniqueIdUTF8) { if (!deviceUniqueIdUTF8[0]) { return NULL; } - rtc::scoped_refptr capture_module(new rtc::RefCountedObject()); + rtc::scoped_refptr capture_module( + new rtc::RefCountedObject()); const int32_t name_length = strlen(deviceUniqueIdUTF8); if (name_length >= kVideoCaptureUniqueNameLength) return nullptr; @@ -65,14 +68,16 @@ rtc::scoped_refptr VideoCaptureIos::Create(const char* devic } if (![capture_module->capture_device_ - setCaptureDeviceByUniqueId:[[NSString alloc] initWithCString:deviceUniqueIdUTF8 - encoding:NSUTF8StringEncoding]]) { + setCaptureDeviceByUniqueId: + [[NSString alloc] initWithCString:deviceUniqueIdUTF8 + encoding:NSUTF8StringEncoding]]) { return nullptr; } return capture_module; } -int32_t VideoCaptureIos::StartCapture(const VideoCaptureCapability& capability) { +int32_t VideoCaptureIos::StartCapture( + const VideoCaptureCapability& capability) { capability_ = capability; if (![capture_device_ startCaptureWithCapability:capability]) { diff --git a/dom/media/systemservices/objc_video_capture/video_capture_avfoundation.mm b/dom/media/systemservices/objc_video_capture/video_capture_avfoundation.mm index e5ca826fa4e6..746bf86f020d 100644 --- a/dom/media/systemservices/objc_video_capture/video_capture_avfoundation.mm +++ b/dom/media/systemservices/objc_video_capture/video_capture_avfoundation.mm @@ -38,30 +38,37 @@ webrtc::VideoRotation ToNativeRotation(RTCVideoRotation aRotation) { case RTCVideoRotation_270: return webrtc::kVideoRotation_270; default: - MOZ_CRASH_UNSAFE_PRINTF("Unexpected rotation %d", static_cast(aRotation)); + MOZ_CRASH_UNSAFE_PRINTF("Unexpected rotation %d", + static_cast(aRotation)); return webrtc::kVideoRotation_0; } } -AVCaptureDeviceFormat* _Nullable FindFormat(AVCaptureDevice* _Nonnull aDevice, - webrtc::VideoCaptureCapability aCapability) { +AVCaptureDeviceFormat* _Nullable FindFormat( + AVCaptureDevice* _Nonnull aDevice, + webrtc::VideoCaptureCapability aCapability) { for (AVCaptureDeviceFormat* format in [aDevice formats]) { - CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription); + CMVideoDimensions dimensions = + CMVideoFormatDescriptionGetDimensions(format.formatDescription); if (dimensions.width != aCapability.width) { continue; } if (dimensions.height != aCapability.height) { continue; } - FourCharCode fourcc = CMFormatDescriptionGetMediaSubType(format.formatDescription); - if (aCapability.videoType != DeviceInfoAvFoundation::ConvertFourCCToVideoType(fourcc)) { + FourCharCode fourcc = + CMFormatDescriptionGetMediaSubType(format.formatDescription); + if (aCapability.videoType != + DeviceInfoAvFoundation::ConvertFourCCToVideoType(fourcc)) { continue; } if ([format.videoSupportedFrameRateRanges - indexOfObjectPassingTest:^BOOL(AVFrameRateRange* _Nonnull obj, NSUInteger idx, + indexOfObjectPassingTest:^BOOL(AVFrameRateRange* _Nonnull obj, + NSUInteger idx, BOOL* _Nonnull stop) { - return static_cast(DeviceInfoAvFoundation::ConvertAVFrameRateToCapabilityFPS( - obj.maxFrameRate) == aCapability.maxFPS); + return static_cast( + DeviceInfoAvFoundation::ConvertAVFrameRateToCapabilityFPS( + obj.maxFrameRate) == aCapability.maxFPS); }] == NSNotFound) { continue; } @@ -73,7 +80,8 @@ AVCaptureDeviceFormat* _Nullable FindFormat(AVCaptureDevice* _Nonnull aDevice, } // namespace @implementation VideoCaptureAdapter -- (void)setCapturer:(webrtc::videocapturemodule::VideoCaptureAvFoundation* _Nullable)capturer { +- (void)setCapturer: + (webrtc::videocapturemodule::VideoCaptureAvFoundation* _Nullable)capturer { webrtc::MutexLock lock(&_mutex); _capturer = capturer; } @@ -91,10 +99,12 @@ AVCaptureDeviceFormat* _Nullable FindFormat(AVCaptureDevice* _Nonnull aDevice, @end namespace webrtc::videocapturemodule { -VideoCaptureAvFoundation::VideoCaptureAvFoundation(AVCaptureDevice* _Nonnull aDevice) +VideoCaptureAvFoundation::VideoCaptureAvFoundation( + AVCaptureDevice* _Nonnull aDevice) : mDevice(aDevice), mAdapter([[VideoCaptureAdapter alloc] init]), - mCapturer([[RTC_OBJC_TYPE(RTCCameraVideoCapturer) alloc] initWithDelegate:mAdapter]), + mCapturer([[RTC_OBJC_TYPE(RTCCameraVideoCapturer) alloc] + initWithDelegate:mAdapter]), mCallbackThreadId() { const char* uniqueId = [[aDevice uniqueID] UTF8String]; size_t len = strlen(uniqueId); @@ -123,7 +133,8 @@ rtc::scoped_refptr VideoCaptureAvFoundation::Create( return nullptr; } -int32_t VideoCaptureAvFoundation::StartCapture(const VideoCaptureCapability& aCapability) { +int32_t VideoCaptureAvFoundation::StartCapture( + const VideoCaptureCapability& aCapability) { RTC_DCHECK_RUN_ON(&mChecker); AVCaptureDeviceFormat* format = FindFormat(mDevice, aCapability); if (!format) { @@ -133,7 +144,8 @@ int32_t VideoCaptureAvFoundation::StartCapture(const VideoCaptureCapability& aCa { MutexLock lock(&api_lock_); if (mCapability) { - if (mCapability->width == aCapability.width && mCapability->height == aCapability.height && + if (mCapability->width == aCapability.width && + mCapability->height == aCapability.height && mCapability->maxFPS == aCapability.maxFPS && mCapability->videoType == aCapability.videoType) { return 0; @@ -250,28 +262,33 @@ bool VideoCaptureAvFoundation::CaptureStarted() { return mCapability.isSome(); } -int32_t VideoCaptureAvFoundation::CaptureSettings(VideoCaptureCapability& aSettings) { +int32_t VideoCaptureAvFoundation::CaptureSettings( + VideoCaptureCapability& aSettings) { MOZ_CRASH("Unexpected call"); return -1; } -int32_t VideoCaptureAvFoundation::OnFrame(__strong RTCVideoFrame* _Nonnull aFrame) { +int32_t VideoCaptureAvFoundation::OnFrame( + __strong RTCVideoFrame* _Nonnull aFrame) { MaybeRegisterCallbackThread(); if (MutexLock lock(&api_lock_); MOZ_LIKELY(mTrackingId)) { - mCaptureRecorder.Start(0, "VideoCaptureAVFoundation"_ns, *mTrackingId, aFrame.width, - aFrame.height, mImageType.valueOr(CaptureStage::ImageType::Unknown)); + mCaptureRecorder.Start( + 0, "VideoCaptureAVFoundation"_ns, *mTrackingId, aFrame.width, + aFrame.height, mImageType.valueOr(CaptureStage::ImageType::Unknown)); if (mCapability && mCapability->videoType != webrtc::VideoType::kI420) { - mConversionRecorder.Start(0, "VideoCaptureAVFoundation"_ns, *mTrackingId, aFrame.width, - aFrame.height); + mConversionRecorder.Start(0, "VideoCaptureAVFoundation"_ns, *mTrackingId, + aFrame.width, aFrame.height); } } - const int64_t timestamp_us = aFrame.timeStampNs / rtc::kNumNanosecsPerMicrosec; + const int64_t timestamp_us = + aFrame.timeStampNs / rtc::kNumNanosecsPerMicrosec; RTCI420Buffer* buffer = [aFrame.buffer toI420]; mConversionRecorder.Record(0); - // Accessing the (intended-to-be-private) native buffer directly is hacky but lets us skip two - // copies - rtc::scoped_refptr nativeBuffer = buffer.nativeI420Buffer; + // Accessing the (intended-to-be-private) native buffer directly is hacky but + // lets us skip two copies + rtc::scoped_refptr nativeBuffer = + buffer.nativeI420Buffer; auto frame = webrtc::VideoFrame::Builder() .set_video_frame_buffer(nativeBuffer) .set_rotation(ToNativeRotation(aFrame.rotation)) @@ -288,8 +305,8 @@ void VideoCaptureAvFoundation::SetTrackingId(uint32_t aTrackingIdProcId) { RTC_DCHECK_RUN_ON(&mChecker); MutexLock lock(&api_lock_); if (NS_WARN_IF(mTrackingId.isSome())) { - // This capture instance must be shared across multiple camera requests. For now ignore other - // requests than the first. + // This capture instance must be shared across multiple camera requests. For + // now ignore other requests than the first. return; } mTrackingId.emplace(TrackingId::Source::Camera, aTrackingIdProcId); @@ -301,6 +318,7 @@ void VideoCaptureAvFoundation::MaybeRegisterCallbackThread() { return; } mCallbackThreadId = id; - CallbackThreadRegistry::Get()->Register(mCallbackThreadId, "VideoCaptureAVFoundationCallback"); + CallbackThreadRegistry::Get()->Register(mCallbackThreadId, + "VideoCaptureAVFoundationCallback"); } } // namespace webrtc::videocapturemodule diff --git a/dom/media/webspeech/synth/cocoa/OSXSpeechSynthesizerService.mm b/dom/media/webspeech/synth/cocoa/OSXSpeechSynthesizerService.mm index a815c6864442..1c0ecb767979 100644 --- a/dom/media/webspeech/synth/cocoa/OSXSpeechSynthesizerService.mm +++ b/dom/media/webspeech/synth/cocoa/OSXSpeechSynthesizerService.mm @@ -1,4 +1,5 @@ -/* -*- Mode: Objective-C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: Objective-C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: + * 2 -*- */ /* vim: set ts=2 sw=2 et tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this @@ -37,7 +38,8 @@ class SpeechTaskCallback final : public nsISpeechTaskCallback { const nsTArray& aOffsets); NS_DECL_CYCLE_COLLECTING_ISUPPORTS - NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(SpeechTaskCallback, nsISpeechTaskCallback) + NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(SpeechTaskCallback, + nsISpeechTaskCallback) NS_DECL_NSISPEECHTASKCALLBACK @@ -79,7 +81,8 @@ class SpeechTaskCallback final : public nsISpeechTaskCallback { mCallback->OnWillSpeakWord(aRange.location, aRange.length); } -- (void)speechSynthesizer:(NSSpeechSynthesizer*)aSender didFinishSpeaking:(BOOL)aFinishedSpeaking { +- (void)speechSynthesizer:(NSSpeechSynthesizer*)aSender + didFinishSpeaking:(BOOL)aFinishedSpeaking { mCallback->OnDidFinishSpeaking(); } @@ -101,9 +104,13 @@ NS_INTERFACE_MAP_END NS_IMPL_CYCLE_COLLECTING_ADDREF(SpeechTaskCallback) NS_IMPL_CYCLE_COLLECTING_RELEASE(SpeechTaskCallback) -SpeechTaskCallback::SpeechTaskCallback(nsISpeechTask* aTask, NSSpeechSynthesizer* aSynth, +SpeechTaskCallback::SpeechTaskCallback(nsISpeechTask* aTask, + NSSpeechSynthesizer* aSynth, const nsTArray& aOffsets) - : mTask(aTask), mSpeechSynthesizer(aSynth), mCurrentIndex(0), mOffsets(aOffsets.Clone()) { + : mTask(aTask), + mSpeechSynthesizer(aSynth), + mCurrentIndex(0), + mOffsets(aOffsets.Clone()) { mDelegate = [[SpeechDelegate alloc] initWithCallback:this]; [mSpeechSynthesizer setDelegate:mDelegate]; mStartingTime = TimeStamp::Now(); @@ -179,7 +186,8 @@ void SpeechTaskCallback::OnWillSpeakWord(uint32_t aIndex, uint32_t aLength) { if (!mTask) { return; } - mTask->DispatchBoundary(u"word"_ns, GetTimeDurationFromStart(), mCurrentIndex, aLength, 1); + mTask->DispatchBoundary(u"word"_ns, GetTimeDurationFromStart(), mCurrentIndex, + aLength, 1); } void SpeechTaskCallback::OnError(uint32_t aIndex) { @@ -210,8 +218,11 @@ struct OSXVoice { class RegisterVoicesRunnable final : public Runnable { public: - RegisterVoicesRunnable(OSXSpeechSynthesizerService* aSpeechService, nsTArray& aList) - : Runnable("RegisterVoicesRunnable"), mSpeechService(aSpeechService), mVoices(aList) {} + RegisterVoicesRunnable(OSXSpeechSynthesizerService* aSpeechService, + nsTArray& aList) + : Runnable("RegisterVoicesRunnable"), + mSpeechService(aSpeechService), + mVoices(aList) {} NS_IMETHOD Run() override; @@ -226,13 +237,15 @@ class RegisterVoicesRunnable final : public Runnable { NS_IMETHODIMP RegisterVoicesRunnable::Run() { nsresult rv; - nsCOMPtr registry = do_GetService(NS_SYNTHVOICEREGISTRY_CONTRACTID, &rv); + nsCOMPtr registry = + do_GetService(NS_SYNTHVOICEREGISTRY_CONTRACTID, &rv); if (!registry) { return rv; } for (OSXVoice voice : mVoices) { - rv = registry->AddVoice(mSpeechService, voice.mUri, voice.mName, voice.mLocale, true, false); + rv = registry->AddVoice(mSpeechService, voice.mUri, voice.mName, + voice.mLocale, true, false); if (NS_WARN_IF(NS_FAILED(rv))) { continue; } @@ -275,11 +288,14 @@ EnumVoicesRunnable::Run() { NSDictionary* attr = [NSSpeechSynthesizer attributesForVoice:voice]; nsAutoString identifier; - nsCocoaUtils::GetStringForNSString([attr objectForKey:NSVoiceIdentifier], identifier); + nsCocoaUtils::GetStringForNSString([attr objectForKey:NSVoiceIdentifier], + identifier); - nsCocoaUtils::GetStringForNSString([attr objectForKey:NSVoiceName], item.mName); + nsCocoaUtils::GetStringForNSString([attr objectForKey:NSVoiceName], + item.mName); - nsCocoaUtils::GetStringForNSString([attr objectForKey:NSVoiceLocaleIdentifier], item.mLocale); + nsCocoaUtils::GetStringForNSString( + [attr objectForKey:NSVoiceLocaleIdentifier], item.mLocale); item.mLocale.ReplaceChar('_', '-'); item.mUri.AssignLiteral("urn:moz-tts:osx:"); @@ -292,16 +308,19 @@ EnumVoicesRunnable::Run() { list.AppendElement(item); } - RefPtr runnable = new RegisterVoicesRunnable(mSpeechService, list); + RefPtr runnable = + new RegisterVoicesRunnable(mSpeechService, list); NS_DispatchAndSpinEventLoopUntilComplete("EnumVoicesRunnable"_ns, - GetMainThreadSerialEventTarget(), runnable.forget()); + GetMainThreadSerialEventTarget(), + runnable.forget()); return NS_OK; NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -StaticRefPtr OSXSpeechSynthesizerService::sSingleton; +StaticRefPtr + OSXSpeechSynthesizerService::sSingleton; NS_INTERFACE_MAP_BEGIN(OSXSpeechSynthesizerService) NS_INTERFACE_MAP_ENTRY(nsISpeechService) @@ -312,7 +331,8 @@ NS_INTERFACE_MAP_END NS_IMPL_ADDREF(OSXSpeechSynthesizerService) NS_IMPL_RELEASE(OSXSpeechSynthesizerService) -OSXSpeechSynthesizerService::OSXSpeechSynthesizerService() : mInitialized(false) {} +OSXSpeechSynthesizerService::OSXSpeechSynthesizerService() + : mInitialized(false) {} bool OSXSpeechSynthesizerService::Init() { if (Preferences::GetBool("media.webspeech.synth.test") || @@ -335,8 +355,10 @@ bool OSXSpeechSynthesizerService::Init() { } NS_IMETHODIMP -OSXSpeechSynthesizerService::Speak(const nsAString& aText, const nsAString& aUri, float aVolume, - float aRate, float aPitch, nsISpeechTask* aTask) { +OSXSpeechSynthesizerService::Speak(const nsAString& aText, + const nsAString& aUri, float aVolume, + float aRate, float aPitch, + nsISpeechTask* aTask) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; MOZ_ASSERT(StringBeginsWith(aUri, u"urn:moz-tts:osx:"_ns), @@ -348,11 +370,16 @@ OSXSpeechSynthesizerService::Speak(const nsAString& aText, const nsAString& aUri [synth setVoice:identifier]; // default rate is 180-220 - [synth setObject:[NSNumber numberWithInt:aRate * 200] forProperty:NSSpeechRateProperty error:nil]; + [synth setObject:[NSNumber numberWithInt:aRate * 200] + forProperty:NSSpeechRateProperty + error:nil]; // volume allows 0.0-1.0 - [synth setObject:[NSNumber numberWithFloat:aVolume] forProperty:NSSpeechVolumeProperty error:nil]; + [synth setObject:[NSNumber numberWithFloat:aVolume] + forProperty:NSSpeechVolumeProperty + error:nil]; // Use default pitch value to calculate this - NSNumber* defaultPitch = [synth objectForProperty:NSSpeechPitchBaseProperty error:nil]; + NSNumber* defaultPitch = [synth objectForProperty:NSSpeechPitchBaseProperty + error:nil]; if (defaultPitch) { int newPitch = [defaultPitch intValue] * (aPitch / 2 + 0.5); [synth setObject:[NSNumber numberWithInt:newPitch] @@ -370,8 +397,8 @@ OSXSpeechSynthesizerService::Speak(const nsAString& aText, const nsAString& aUri // This loop looks for occurances of "[[" or "]]", escapes them, and // populates the offsets array to supply a map to the original offsets. for (size_t i = 0; i < aText.Length(); i++) { - if (aText.Length() > i + 1 && - ((aText[i] == ']' && aText[i + 1] == ']') || (aText[i] == '[' && aText[i + 1] == '['))) { + if (aText.Length() > i + 1 && ((aText[i] == ']' && aText[i + 1] == ']') || + (aText[i] == '[' && aText[i + 1] == '['))) { escapedText.AppendLiteral(DLIM_ESCAPE_START); offsets.AppendElements(strlen(DLIM_ESCAPE_START)); escapedText.Append(aText[i]); @@ -386,7 +413,8 @@ OSXSpeechSynthesizerService::Speak(const nsAString& aText, const nsAString& aUri } } - RefPtr callback = new SpeechTaskCallback(aTask, synth, offsets); + RefPtr callback = + new SpeechTaskCallback(aTask, synth, offsets); nsresult rv = aTask->Setup(callback); NS_ENSURE_SUCCESS(rv, rv); @@ -413,7 +441,8 @@ OSXSpeechSynthesizerService* OSXSpeechSynthesizerService::GetInstance() { } if (!sSingleton) { - RefPtr speechService = new OSXSpeechSynthesizerService(); + RefPtr speechService = + new OSXSpeechSynthesizerService(); if (speechService->Init()) { sSingleton = speechService; ClearOnShutdown(&sSingleton); @@ -422,7 +451,8 @@ OSXSpeechSynthesizerService* OSXSpeechSynthesizerService::GetInstance() { return sSingleton; } -already_AddRefed OSXSpeechSynthesizerService::GetInstanceForService() { +already_AddRefed +OSXSpeechSynthesizerService::GetInstanceForService() { RefPtr speechService = GetInstance(); return speechService.forget(); } diff --git a/dom/system/mac/CoreLocationLocationProvider.mm b/dom/system/mac/CoreLocationLocationProvider.mm index d7ea6da34115..f3358a7fb761 100644 --- a/dom/system/mac/CoreLocationLocationProvider.mm +++ b/dom/system/mac/CoreLocationLocationProvider.mm @@ -29,15 +29,18 @@ using namespace mozilla; static const CLLocationAccuracy kHIGH_ACCURACY = kCLLocationAccuracyBest; -static const CLLocationAccuracy kDEFAULT_ACCURACY = kCLLocationAccuracyNearestTenMeters; +static const CLLocationAccuracy kDEFAULT_ACCURACY = + kCLLocationAccuracyNearestTenMeters; @interface LocationDelegate : NSObject { CoreLocationLocationProvider* mProvider; } - (id)init:(CoreLocationLocationProvider*)aProvider; -- (void)locationManager:(CLLocationManager*)aManager didFailWithError:(NSError*)aError; -- (void)locationManager:(CLLocationManager*)aManager didUpdateLocations:(NSArray*)locations; +- (void)locationManager:(CLLocationManager*)aManager + didFailWithError:(NSError*)aError; +- (void)locationManager:(CLLocationManager*)aManager + didUpdateLocations:(NSArray*)locations; @end @@ -50,28 +53,32 @@ static const CLLocationAccuracy kDEFAULT_ACCURACY = kCLLocationAccuracyNearestTe return self; } -- (void)locationManager:(CLLocationManager*)aManager didFailWithError:(NSError*)aError { - nsCOMPtr console = do_GetService(NS_CONSOLESERVICE_CONTRACTID); +- (void)locationManager:(CLLocationManager*)aManager + didFailWithError:(NSError*)aError { + nsCOMPtr console = + do_GetService(NS_CONSOLESERVICE_CONTRACTID); NS_ENSURE_TRUE_VOID(console); - NSString* message = - [@"Failed to acquire position: " stringByAppendingString:[aError localizedDescription]]; + NSString* message = [@"Failed to acquire position: " + stringByAppendingString:[aError localizedDescription]]; console->LogStringMessage(NS_ConvertUTF8toUTF16([message UTF8String]).get()); if ([aError code] == kCLErrorDenied) { - mProvider->NotifyError(dom::GeolocationPositionError_Binding::PERMISSION_DENIED); + mProvider->NotifyError( + dom::GeolocationPositionError_Binding::PERMISSION_DENIED); return; } - // The CL provider does not fallback to GeoIP, so use NetworkGeolocationProvider for this. - // The concept here is: on error, hand off geolocation to MLS, which will then report - // back a location or error. + // The CL provider does not fallback to GeoIP, so use + // NetworkGeolocationProvider for this. The concept here is: on error, hand + // off geolocation to MLS, which will then report back a location or error. mProvider->CreateMLSFallbackProvider(); } -- (void)locationManager:(CLLocationManager*)aManager didUpdateLocations:(NSArray*)aLocations { +- (void)locationManager:(CLLocationManager*)aManager + didUpdateLocations:(NSArray*)aLocations { if (aLocations.count < 1) { return; } @@ -92,24 +99,29 @@ static const CLLocationAccuracy kDEFAULT_ACCURACY = kCLLocationAccuracyNearestTe altitudeAccuracy = UnspecifiedNaN(); } - double speed = location.speed >= 0 ? location.speed : UnspecifiedNaN(); + double speed = + location.speed >= 0 ? location.speed : UnspecifiedNaN(); - double heading = location.course >= 0 ? location.course : UnspecifiedNaN(); + double heading = + location.course >= 0 ? location.course : UnspecifiedNaN(); // nsGeoPositionCoords will convert NaNs to null for optional properties of // the JavaScript Coordinates object. nsCOMPtr geoPosition = new nsGeoPosition( location.coordinate.latitude, location.coordinate.longitude, altitude, - location.horizontalAccuracy, altitudeAccuracy, heading, speed, PR_Now() / PR_USEC_PER_MSEC); + location.horizontalAccuracy, altitudeAccuracy, heading, speed, + PR_Now() / PR_USEC_PER_MSEC); mProvider->Update(geoPosition); Telemetry::Accumulate(Telemetry::GEOLOCATION_OSX_SOURCE_IS_MLS, false); } @end -NS_IMPL_ISUPPORTS(CoreLocationLocationProvider::MLSUpdate, nsIGeolocationUpdate); +NS_IMPL_ISUPPORTS(CoreLocationLocationProvider::MLSUpdate, + nsIGeolocationUpdate); -CoreLocationLocationProvider::MLSUpdate::MLSUpdate(CoreLocationLocationProvider& parentProvider) +CoreLocationLocationProvider::MLSUpdate::MLSUpdate( + CoreLocationLocationProvider& parentProvider) : mParentLocationProvider(parentProvider) {} NS_IMETHODIMP @@ -175,7 +187,8 @@ CoreLocationLocationProvider::Startup() { mCLObjects = clObjs.release(); } - // Must be stopped before starting or response (success or failure) is not guaranteed + // Must be stopped before starting or response (success or failure) is not + // guaranteed [mCLObjects->mLocationManager stopUpdatingLocation]; [mCLObjects->mLocationManager startUpdatingLocation]; return NS_OK; @@ -212,7 +225,8 @@ NS_IMETHODIMP CoreLocationLocationProvider::SetHighAccuracy(bool aEnable) { NS_ENSURE_STATE(mCLObjects); - mCLObjects->mLocationManager.desiredAccuracy = (aEnable ? kHIGH_ACCURACY : kDEFAULT_ACCURACY); + mCLObjects->mLocationManager.desiredAccuracy = + (aEnable ? kHIGH_ACCURACY : kDEFAULT_ACCURACY); return NS_OK; } diff --git a/dom/system/mac/nsOSPermissionRequest.mm b/dom/system/mac/nsOSPermissionRequest.mm index 7104a91f1c28..82e9edf1ace9 100644 --- a/dom/system/mac/nsOSPermissionRequest.mm +++ b/dom/system/mac/nsOSPermissionRequest.mm @@ -32,7 +32,8 @@ nsOSPermissionRequest::GetScreenCapturePermissionState(uint16_t* aScreen) { } NS_IMETHODIMP -nsOSPermissionRequest::RequestVideoCapturePermission(JSContext* aCx, Promise** aPromiseOut) { +nsOSPermissionRequest::RequestVideoCapturePermission(JSContext* aCx, + Promise** aPromiseOut) { RefPtr promiseHandle; nsresult rv = GetPromise(aCx, promiseHandle); if (NS_FAILED(rv)) { @@ -45,7 +46,8 @@ nsOSPermissionRequest::RequestVideoCapturePermission(JSContext* aCx, Promise** a } NS_IMETHODIMP -nsOSPermissionRequest::RequestAudioCapturePermission(JSContext* aCx, Promise** aPromiseOut) { +nsOSPermissionRequest::RequestAudioCapturePermission(JSContext* aCx, + Promise** aPromiseOut) { RefPtr promiseHandle; nsresult rv = GetPromise(aCx, promiseHandle); if (NS_FAILED(rv)) { diff --git a/gfx/gl/GLContextProviderCGL.mm b/gfx/gl/GLContextProviderCGL.mm index 1b4049de3e71..1608ebb9e5d0 100644 --- a/gfx/gl/GLContextProviderCGL.mm +++ b/gfx/gl/GLContextProviderCGL.mm @@ -37,7 +37,8 @@ class CGLLibrary { return true; } if (!mOGLLibrary) { - mOGLLibrary = PR_LoadLibrary("/System/Library/Frameworks/OpenGL.framework/OpenGL"); + mOGLLibrary = + PR_LoadLibrary("/System/Library/Frameworks/OpenGL.framework/OpenGL"); if (!mOGLLibrary) { NS_WARNING("Couldn't load OpenGL Framework."); return false; @@ -59,7 +60,8 @@ CGLLibrary sCGLLibrary; GLContextCGL::GLContextCGL(const GLContextDesc& desc, NSOpenGLContext* context) : GLContext(desc), mContext(context) { - CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallback, this); + CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallback, + this); } GLContextCGL::~GLContextCGL() { @@ -89,33 +91,39 @@ bool GLContextCGL::MakeCurrentImpl() const { // Use non-blocking swap in "ASAP mode". // ASAP mode means that rendering is iterated as fast as possible. // ASAP mode is entered when layout.frame_rate=0 (requires restart). - // If swapInt is 1, then glSwapBuffers will block and wait for a vblank signal. - // When we're iterating as fast as possible, however, we want a non-blocking - // glSwapBuffers, which will happen when swapInt==0. + // If swapInt is 1, then glSwapBuffers will block and wait for a vblank + // signal. When we're iterating as fast as possible, however, we want a + // non-blocking glSwapBuffers, which will happen when swapInt==0. GLint swapInt = StaticPrefs::layout_frame_rate() == 0 ? 0 : 1; [mContext setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; } return true; } -bool GLContextCGL::IsCurrentImpl() const { return [NSOpenGLContext currentContext] == mContext; } +bool GLContextCGL::IsCurrentImpl() const { + return [NSOpenGLContext currentContext] == mContext; +} -/* static */ void GLContextCGL::DisplayReconfigurationCallback(CGDirectDisplayID aDisplay, - CGDisplayChangeSummaryFlags aFlags, - void* aUserInfo) { +/* static */ void GLContextCGL::DisplayReconfigurationCallback( + CGDirectDisplayID aDisplay, CGDisplayChangeSummaryFlags aFlags, + void* aUserInfo) { if (aFlags & kCGDisplaySetModeFlag) { - static_cast(aUserInfo)->mActiveGPUSwitchMayHaveOccurred = true; + static_cast(aUserInfo)->mActiveGPUSwitchMayHaveOccurred = + true; } } -static NSOpenGLContext* CreateWithFormat(const NSOpenGLPixelFormatAttribute* attribs) { - NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; +static NSOpenGLContext* CreateWithFormat( + const NSOpenGLPixelFormatAttribute* attribs) { + NSOpenGLPixelFormat* format = + [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; if (!format) { NS_WARNING("Failed to create NSOpenGLPixelFormat."); return nullptr; } - NSOpenGLContext* context = [[NSOpenGLContext alloc] initWithFormat:format shareContext:nullptr]; + NSOpenGLContext* context = [[NSOpenGLContext alloc] initWithFormat:format + shareContext:nullptr]; [format release]; @@ -124,30 +132,40 @@ static NSOpenGLContext* CreateWithFormat(const NSOpenGLPixelFormatAttribute* att // Get the "OpenGL display mask" for a fresh context. The return value of this // function depends on the time at which this function is called. -// In practice, on a Macbook Pro with an integrated and a discrete GPU, this function returns the -// display mask for the GPU that currently drives the internal display. +// In practice, on a Macbook Pro with an integrated and a discrete GPU, this +// function returns the display mask for the GPU that currently drives the +// internal display. // // Quick reference of the concepts involved in the code below: -// GPU switch: On Mac devices with an integrated and a discrete GPU, a GPU switch changes which -// GPU drives the internal display. Both GPUs are still usable at all times. (When the -// integrated GPU is driving the internal display, using the discrete GPU can incur a longer -// warm-up cost.) -// Virtual screen: A CGL concept. A "virtual screen" corresponds to a GL renderer. There's one -// for the integrated GPU, one for each discrete GPU, and one for the Apple software renderer. -// The list of virtual screens is per-NSOpenGLPixelFormat; it is filtered down to only the -// renderers that support the requirements from the pixel format attributes. Indexes into this -// list (such as currentVirtualScreen) cannot be used interchangably across different -// NSOpenGLPixelFormat instances. -// Display mask: A bitset per GL renderer. Different renderers have disjoint display masks. The +// GPU switch: On Mac devices with an integrated and a discrete GPU, a GPU +// switch changes which +// GPU drives the internal display. Both GPUs are still usable at all times. +// (When the integrated GPU is driving the internal display, using the +// discrete GPU can incur a longer warm-up cost.) +// Virtual screen: A CGL concept. A "virtual screen" corresponds to a GL +// renderer. There's one +// for the integrated GPU, one for each discrete GPU, and one for the Apple +// software renderer. The list of virtual screens is +// per-NSOpenGLPixelFormat; it is filtered down to only the renderers that +// support the requirements from the pixel format attributes. Indexes into +// this list (such as currentVirtualScreen) cannot be used interchangably +// across different NSOpenGLPixelFormat instances. +// Display mask: A bitset per GL renderer. Different renderers have disjoint +// display masks. The // Apple software renderer has all bits zeroed. For each CGDirectDisplayID, -// CGDisplayIDToOpenGLDisplayMask(displayID) returns a single bit in the display mask. -// CGDirectDisplayID: An ID for each (physical screen, GPU which can drive this screen) pair. The -// current CGDirectDisplayID for an NSScreen object can be obtained using [[[screen -// deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue]; it changes depending on -// which GPU is currently driving the screen. +// CGDisplayIDToOpenGLDisplayMask(displayID) returns a single bit in the +// display mask. +// CGDirectDisplayID: An ID for each (physical screen, GPU which can drive +// this screen) pair. The +// current CGDirectDisplayID for an NSScreen object can be obtained using +// [[[screen deviceDescription] objectForKey:@"NSScreenNumber"] +// unsignedIntValue]; it changes depending on which GPU is currently driving +// the screen. static CGOpenGLDisplayMask GetFreshContextDisplayMask() { - NSOpenGLPixelFormatAttribute attribs[] = {NSOpenGLPFAAllowOfflineRenderers, 0}; - NSOpenGLPixelFormat* pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; + NSOpenGLPixelFormatAttribute attribs[] = {NSOpenGLPFAAllowOfflineRenderers, + 0}; + NSOpenGLPixelFormat* pixelFormat = + [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; MOZ_RELEASE_ASSERT(pixelFormat); NSOpenGLContext* context = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nullptr]; @@ -185,13 +203,15 @@ void GLContextCGL::MigrateToActiveGPU() { return; } - // Find the "virtual screen" with a display mask that matches newPreferredDisplayMask, if - // available, and switch the context over to it. - // This code was inspired by equivalent functionality in -[NSOpenGLContext update] which only - // kicks in for contexts that present via a CAOpenGLLayer. + // Find the "virtual screen" with a display mask that matches + // newPreferredDisplayMask, if available, and switch the context over to it. + // This code was inspired by equivalent functionality in -[NSOpenGLContext + // update] which only kicks in for contexts that present via a CAOpenGLLayer. for (const auto i : IntegerRange([pixelFormat numberOfVirtualScreens])) { GLint displayMask = 0; - [pixelFormat getValues:&displayMask forAttribute:NSOpenGLPFAScreenMask forVirtualScreen:i]; + [pixelFormat getValues:&displayMask + forAttribute:NSOpenGLPFAScreenMask + forVirtualScreen:i]; if (IsSameGPU(displayMask, newPreferredDisplayMask)) { CGLSetVirtualScreen([mContext CGLContextObj], i); return; @@ -212,7 +232,9 @@ bool GLContextCGL::SwapBuffers() { return true; } -void GLContextCGL::GetWSIInfo(nsCString* const out) const { out->AppendLiteral("CGL"); } +void GLContextCGL::GetWSIInfo(nsCString* const out) const { + out->AppendLiteral("CGL"); +} Maybe GLContextCGL::GetSymbolLoader() const { const auto& lib = sCGLLibrary.Library(); @@ -220,7 +242,8 @@ Maybe GLContextCGL::GetSymbolLoader() const { } already_AddRefed GLContextProviderCGL::CreateForCompositorWidget( - CompositorWidget* aCompositorWidget, bool aHardwareWebRender, bool aForceAccelerated) { + CompositorWidget* aCompositorWidget, bool aHardwareWebRender, + bool aForceAccelerated) { CreateContextFlags flags = CreateContextFlags::ALLOW_OFFLINE_RENDERER; if (aForceAccelerated) { flags |= CreateContextFlags::FORBID_SOFTWARE; @@ -232,7 +255,8 @@ already_AddRefed GLContextProviderCGL::CreateForCompositorWidget( return CreateHeadless({flags}, &failureUnused); } -static RefPtr CreateOffscreenFBOContext(GLContextCreateDesc desc) { +static RefPtr CreateOffscreenFBOContext( + GLContextCreateDesc desc) { if (!sCGLLibrary.EnsureInitialized()) { return nullptr; } @@ -247,8 +271,9 @@ static RefPtr CreateOffscreenFBOContext(GLContextCreateDesc desc) } if (flags & CreateContextFlags::ALLOW_OFFLINE_RENDERER || !(flags & CreateContextFlags::HIGH_POWER)) { - // This is really poorly named on Apple's part, but "AllowOfflineRenderers" means - // that we want to allow running on the iGPU instead of requiring the dGPU. + // This is really poorly named on Apple's part, but "AllowOfflineRenderers" + // means that we want to allow running on the iGPU instead of requiring the + // dGPU. attribs.push_back(NSOpenGLPFAAllowOfflineRenderers); } @@ -298,8 +323,8 @@ static RefPtr CreateOffscreenFBOContext(GLContextCreateDesc desc) return glContext; } -already_AddRefed GLContextProviderCGL::CreateHeadless(const GLContextCreateDesc& desc, - nsACString* const out_failureId) { +already_AddRefed GLContextProviderCGL::CreateHeadless( + const GLContextCreateDesc& desc, nsACString* const out_failureId) { auto gl = CreateOffscreenFBOContext(desc); if (!gl) { *out_failureId = "FEATURE_FAILURE_CGL_FBO"_ns; diff --git a/gfx/gl/GLContextProviderEAGL.mm b/gfx/gl/GLContextProviderEAGL.mm index 4aabe89df1de..a314bd672dcf 100644 --- a/gfx/gl/GLContextProviderEAGL.mm +++ b/gfx/gl/GLContextProviderEAGL.mm @@ -52,7 +52,8 @@ bool GLContextEAGL::AttachToWindow(nsIWidget* aWidget) { // This should only be called once MOZ_ASSERT(!mBackbufferFB && !mBackbufferRB); - UIView* view = reinterpret_cast(aWidget->GetNativeData(NS_NATIVE_WIDGET)); + UIView* view = + reinterpret_cast(aWidget->GetNativeData(NS_NATIVE_WIDGET)); if (!view) { MOZ_CRASH("no view!"); @@ -82,10 +83,11 @@ bool GLContextEAGL::RecreateRB() { [mContext renderbufferStorage:LOCAL_GL_RENDERBUFFER fromDrawable:layer]; fBindFramebuffer(LOCAL_GL_FRAMEBUFFER, mBackbufferFB); - fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_COLOR_ATTACHMENT0, LOCAL_GL_RENDERBUFFER, - mBackbufferRB); + fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_COLOR_ATTACHMENT0, + LOCAL_GL_RENDERBUFFER, mBackbufferRB); - return LOCAL_GL_FRAMEBUFFER_COMPLETE == fCheckFramebufferStatus(LOCAL_GL_FRAMEBUFFER); + return LOCAL_GL_FRAMEBUFFER_COMPLETE == + fCheckFramebufferStatus(LOCAL_GL_FRAMEBUFFER); } bool GLContextEAGL::MakeCurrentImpl() const { @@ -97,7 +99,9 @@ bool GLContextEAGL::MakeCurrentImpl() const { return true; } -bool GLContextEAGL::IsCurrentImpl() const { return [EAGLContext currentContext] == mContext; } +bool GLContextEAGL::IsCurrentImpl() const { + return [EAGLContext currentContext] == mContext; +} static PRFuncPtr GLAPIENTRY GetLoadedProcAddress(const char* const name) { PRLibrary* lib = nullptr; @@ -121,7 +125,9 @@ bool GLContextEAGL::SwapBuffers() { return true; } -void GLContextEAGL::GetWSIInfo(nsCString* const out) const { out->AppendLiteral("EAGL"); } +void GLContextEAGL::GetWSIInfo(nsCString* const out) const { + out->AppendLiteral("EAGL"); +} static GLContextEAGL* GetGlobalContextEAGL() { return static_cast(GLContextProviderEAGL::GetGlobalContext()); @@ -129,14 +135,16 @@ static GLContextEAGL* GetGlobalContextEAGL() { static RefPtr CreateEAGLContext(const GLContextDesc& desc, GLContextEAGL* sharedContext) { - EAGLRenderingAPI apis[] = {kEAGLRenderingAPIOpenGLES3, kEAGLRenderingAPIOpenGLES2}; + EAGLRenderingAPI apis[] = {kEAGLRenderingAPIOpenGLES3, + kEAGLRenderingAPIOpenGLES2}; // Try to create a GLES3 context if we can, otherwise fall back to GLES2 EAGLContext* context = nullptr; for (EAGLRenderingAPI api : apis) { if (sharedContext) { - context = [[EAGLContext alloc] initWithAPI:api - sharegroup:sharedContext->GetEAGLContext().sharegroup]; + context = [[EAGLContext alloc] + initWithAPI:api + sharegroup:sharedContext->GetEAGLContext().sharegroup]; } else { context = [[EAGLContext alloc] initWithAPI:api]; } @@ -150,7 +158,8 @@ static RefPtr CreateEAGLContext(const GLContextDesc& desc, return nullptr; } - RefPtr glContext = new GLContextEAGL(desc, context, sharedContext); + RefPtr glContext = + new GLContextEAGL(desc, context, sharedContext); if (!glContext->Init()) { glContext = nullptr; return nullptr; @@ -160,7 +169,8 @@ static RefPtr CreateEAGLContext(const GLContextDesc& desc, } already_AddRefed GLContextProviderEAGL::CreateForCompositorWidget( - CompositorWidget* aCompositorWidget, bool aHardwareWebRender, bool aForceAccelerated) { + CompositorWidget* aCompositorWidget, bool aHardwareWebRender, + bool aForceAccelerated) { if (!aCompositorWidget) { MOZ_ASSERT(false); return nullptr; @@ -172,7 +182,8 @@ already_AddRefed GLContextProviderEAGL::CreateForCompositorWidget( return nullptr; } - if (!GLContextEAGL::Cast(glContext)->AttachToWindow(aCompositorWidget->RealWidget())) { + if (!GLContextEAGL::Cast(glContext)->AttachToWindow( + aCompositorWidget->RealWidget())) { return nullptr; } @@ -193,7 +204,8 @@ GLContext* GLContextProviderEAGL::GetGlobalContext() { if (!triedToCreateContext) { triedToCreateContext = true; - MOZ_RELEASE_ASSERT(!gGlobalContext, "GFX: Global GL context already initialized."); + MOZ_RELEASE_ASSERT(!gGlobalContext, + "GFX: Global GL context already initialized."); RefPtr temp = CreateHeadless(CreateContextFlags::NONE); gGlobalContext = temp; diff --git a/gfx/layers/NativeLayerCA.mm b/gfx/layers/NativeLayerCA.mm index 1fb0a9eb9f6c..fb434dc84fc0 100644 --- a/gfx/layers/NativeLayerCA.mm +++ b/gfx/layers/NativeLayerCA.mm @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nullptr; c-basic-offset: 2 -*- +/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -48,14 +48,15 @@ using gfx::SurfaceFormat; using gl::GLContext; using gl::GLContextCGL; -static Maybe VideoLowPowerTypeToTelemetryType( - VideoLowPowerType aVideoLowPower) { +static Maybe +VideoLowPowerTypeToTelemetryType(VideoLowPowerType aVideoLowPower) { switch (aVideoLowPower) { case VideoLowPowerType::LowPower: return Some(Telemetry::LABELS_GFX_MACOS_VIDEO_LOW_POWER::LowPower); case VideoLowPowerType::FailMultipleVideo: - return Some(Telemetry::LABELS_GFX_MACOS_VIDEO_LOW_POWER::FailMultipleVideo); + return Some( + Telemetry::LABELS_GFX_MACOS_VIDEO_LOW_POWER::FailMultipleVideo); case VideoLowPowerType::FailWindowed: return Some(Telemetry::LABELS_GFX_MACOS_VIDEO_LOW_POWER::FailWindowed); @@ -67,7 +68,8 @@ static Maybe VideoLowPowerTypeToTel return Some(Telemetry::LABELS_GFX_MACOS_VIDEO_LOW_POWER::FailBacking); case VideoLowPowerType::FailMacOSVersion: - return Some(Telemetry::LABELS_GFX_MACOS_VIDEO_LOW_POWER::FailMacOSVersion); + return Some( + Telemetry::LABELS_GFX_MACOS_VIDEO_LOW_POWER::FailMacOSVersion); case VideoLowPowerType::FailPref: return Some(Telemetry::LABELS_GFX_MACOS_VIDEO_LOW_POWER::FailPref); @@ -95,7 +97,8 @@ static void EmitTelemetryForVideoLowPower(VideoLowPowerType aVideoLowPower) { class RenderSourceNLRS : public profiler_screenshots::RenderSource { public: explicit RenderSourceNLRS(UniquePtr&& aFramebuffer) - : RenderSource(aFramebuffer->mSize), mFramebuffer(std::move(aFramebuffer)) {} + : RenderSource(aFramebuffer->mSize), + mFramebuffer(std::move(aFramebuffer)) {} auto& FB() { return *mFramebuffer; } protected: @@ -104,14 +107,17 @@ class RenderSourceNLRS : public profiler_screenshots::RenderSource { class DownscaleTargetNLRS : public profiler_screenshots::DownscaleTarget { public: - DownscaleTargetNLRS(gl::GLContext* aGL, UniquePtr&& aFramebuffer) + DownscaleTargetNLRS(gl::GLContext* aGL, + UniquePtr&& aFramebuffer) : profiler_screenshots::DownscaleTarget(aFramebuffer->mSize), mGL(aGL), mRenderSource(new RenderSourceNLRS(std::move(aFramebuffer))) {} - already_AddRefed AsRenderSource() override { + already_AddRefed AsRenderSource() + override { return do_AddRef(mRenderSource); }; - bool DownscaleFrom(profiler_screenshots::RenderSource* aSource, const IntRect& aSourceRect, + bool DownscaleFrom(profiler_screenshots::RenderSource* aSource, + const IntRect& aSourceRect, const IntRect& aDestRect) override; protected: @@ -119,12 +125,17 @@ class DownscaleTargetNLRS : public profiler_screenshots::DownscaleTarget { RefPtr mRenderSource; }; -class AsyncReadbackBufferNLRS : public profiler_screenshots::AsyncReadbackBuffer { +class AsyncReadbackBufferNLRS + : public profiler_screenshots::AsyncReadbackBuffer { public: - AsyncReadbackBufferNLRS(gl::GLContext* aGL, const IntSize& aSize, GLuint aBufferHandle) - : profiler_screenshots::AsyncReadbackBuffer(aSize), mGL(aGL), mBufferHandle(aBufferHandle) {} + AsyncReadbackBufferNLRS(gl::GLContext* aGL, const IntSize& aSize, + GLuint aBufferHandle) + : profiler_screenshots::AsyncReadbackBuffer(aSize), + mGL(aGL), + mBufferHandle(aBufferHandle) {} void CopyFrom(profiler_screenshots::RenderSource* aSource) override; - bool MapAndCopyInto(DataSourceSurface* aSurface, const IntSize& aReadSize) override; + bool MapAndCopyInto(DataSourceSurface* aSurface, + const IntSize& aReadSize) override; protected: virtual ~AsyncReadbackBufferNLRS(); @@ -133,36 +144,39 @@ class AsyncReadbackBufferNLRS : public profiler_screenshots::AsyncReadbackBuffer }; // Needs to be on the stack whenever CALayer mutations are performed. -// (Mutating CALayers outside of a transaction can result in permanently stuck rendering, because -// such mutations create an implicit transaction which never auto-commits if the current thread does -// not have a native runloop.) -// Uses NSAnimationContext, which wraps CATransaction with additional off-main-thread protection, -// see bug 1585523. +// (Mutating CALayers outside of a transaction can result in permanently stuck +// rendering, because such mutations create an implicit transaction which never +// auto-commits if the current thread does not have a native runloop.) Uses +// NSAnimationContext, which wraps CATransaction with additional off-main-thread +// protection, see bug 1585523. struct MOZ_STACK_CLASS AutoCATransaction final { AutoCATransaction() { [NSAnimationContext beginGrouping]; - // By default, mutating a CALayer property triggers an animation which smoothly transitions the - // property to the new value. We don't need these animations, and this call turns them off: + // By default, mutating a CALayer property triggers an animation which + // smoothly transitions the property to the new value. We don't need these + // animations, and this call turns them off: [CATransaction setDisableActions:YES]; } ~AutoCATransaction() { [NSAnimationContext endGrouping]; } }; -/* static */ already_AddRefed NativeLayerRootCA::CreateForCALayer( - CALayer* aLayer) { +/* static */ already_AddRefed +NativeLayerRootCA::CreateForCALayer(CALayer* aLayer) { RefPtr layerRoot = new NativeLayerRootCA(aLayer); return layerRoot.forget(); } // Returns an autoreleased CALayer* object. static CALayer* MakeOffscreenRootCALayer() { - // This layer should behave similarly to the backing layer of a flipped NSView. - // It will never be rendered on the screen and it will never be attached to an NSView's layer; - // instead, it will be the root layer of a "local" CAContext. - // Setting geometryFlipped to YES causes the orientation of descendant CALayers' contents (such as - // IOSurfaces) to be consistent with what happens in a layer subtree that is attached to a flipped - // NSView. Setting it to NO would cause the surfaces in individual leaf layers to render upside - // down (rather than just flipping the entire layer tree upside down). + // This layer should behave similarly to the backing layer of a flipped + // NSView. It will never be rendered on the screen and it will never be + // attached to an NSView's layer; instead, it will be the root layer of a + // "local" CAContext. Setting geometryFlipped to YES causes the orientation of + // descendant CALayers' contents (such as IOSurfaces) to be consistent with + // what happens in a layer subtree that is attached to a flipped NSView. + // Setting it to NO would cause the surfaces in individual leaf layers to + // render upside down (rather than just flipping the entire layer tree upside + // down). AutoCATransaction transaction; CALayer* layer = [CALayer layer]; layer.position = NSZeroPoint; @@ -180,23 +194,27 @@ NativeLayerRootCA::NativeLayerRootCA(CALayer* aLayer) mOffscreenRepresentation(MakeOffscreenRootCALayer()) {} NativeLayerRootCA::~NativeLayerRootCA() { - MOZ_RELEASE_ASSERT(mSublayers.IsEmpty(), - "Please clear all layers before destroying the layer root."); + MOZ_RELEASE_ASSERT( + mSublayers.IsEmpty(), + "Please clear all layers before destroying the layer root."); } already_AddRefed NativeLayerRootCA::CreateLayer( - const IntSize& aSize, bool aIsOpaque, SurfacePoolHandle* aSurfacePoolHandle) { - RefPtr layer = - new NativeLayerCA(aSize, aIsOpaque, aSurfacePoolHandle->AsSurfacePoolHandleCA()); + const IntSize& aSize, bool aIsOpaque, + SurfacePoolHandle* aSurfacePoolHandle) { + RefPtr layer = new NativeLayerCA( + aSize, aIsOpaque, aSurfacePoolHandle->AsSurfacePoolHandleCA()); return layer.forget(); } -already_AddRefed NativeLayerRootCA::CreateLayerForExternalTexture(bool aIsOpaque) { +already_AddRefed NativeLayerRootCA::CreateLayerForExternalTexture( + bool aIsOpaque) { RefPtr layer = new NativeLayerCA(aIsOpaque); return layer.forget(); } -already_AddRefed NativeLayerRootCA::CreateLayerForColor(gfx::DeviceColor aColor) { +already_AddRefed NativeLayerRootCA::CreateLayerForColor( + gfx::DeviceColor aColor) { RefPtr layer = new NativeLayerCA(aColor); return layer.forget(); } @@ -210,7 +228,8 @@ void NativeLayerRootCA::AppendLayer(NativeLayer* aLayer) { mSublayers.AppendElement(layerCA); layerCA->SetBackingScale(mBackingScale); layerCA->SetRootWindowIsFullscreen(mWindowIsFullscreen); - ForAllRepresentations([&](Representation& r) { r.mMutatedLayerStructure = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedLayerStructure = true; }); } void NativeLayerRootCA::RemoveLayer(NativeLayer* aLayer) { @@ -220,17 +239,20 @@ void NativeLayerRootCA::RemoveLayer(NativeLayer* aLayer) { MOZ_RELEASE_ASSERT(layerCA); mSublayers.RemoveElement(layerCA); - ForAllRepresentations([&](Representation& r) { r.mMutatedLayerStructure = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedLayerStructure = true; }); } -void NativeLayerRootCA::SetLayers(const nsTArray>& aLayers) { +void NativeLayerRootCA::SetLayers( + const nsTArray>& aLayers) { MutexAutoLock lock(mMutex); // Ideally, we'd just be able to do mSublayers = std::move(aLayers). - // However, aLayers has a different type: it carries NativeLayer objects, whereas mSublayers - // carries NativeLayerCA objects, so we have to downcast all the elements first. There's one other - // reason to look at all the elements in aLayers first: We need to make sure any new layers know - // about our current backing scale. + // However, aLayers has a different type: it carries NativeLayer objects, + // whereas mSublayers carries NativeLayerCA objects, so we have to downcast + // all the elements first. There's one other reason to look at all the + // elements in aLayers first: We need to make sure any new layers know about + // our current backing scale. nsTArray> layersCA(aLayers.Length()); for (auto& layer : aLayers) { @@ -243,7 +265,8 @@ void NativeLayerRootCA::SetLayers(const nsTArray>& aLayers) if (layersCA != mSublayers) { mSublayers = std::move(layersCA); - ForAllRepresentations([&](Representation& r) { r.mMutatedLayerStructure = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedLayerStructure = true; }); } } @@ -286,7 +309,8 @@ bool NativeLayerRootCA::CommitToScreen() { return false; } - mOnscreenRepresentation.Commit(WhichRepresentation::ONSCREEN, mSublayers, mWindowIsFullscreen); + mOnscreenRepresentation.Commit(WhichRepresentation::ONSCREEN, mSublayers, + mWindowIsFullscreen); mCommitPending = false; } @@ -296,12 +320,14 @@ bool NativeLayerRootCA::CommitToScreen() { uint32_t frameID = sFrameID++; NSString* dirPath = - [NSString stringWithFormat:@"%@/Desktop/nativelayerdumps-%d", NSHomeDirectory(), getpid()]; + [NSString stringWithFormat:@"%@/Desktop/nativelayerdumps-%d", + NSHomeDirectory(), getpid()]; if ([NSFileManager.defaultManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nullptr]) { - NSString* filename = [NSString stringWithFormat:@"frame-%d.html", frameID]; + NSString* filename = + [NSString stringWithFormat:@"frame-%d.html", frameID]; NSString* filePath = [dirPath stringByAppendingPathComponent:filename]; DumpLayerTreeToFile([filePath UTF8String]); } else { @@ -309,7 +335,8 @@ bool NativeLayerRootCA::CommitToScreen() { } } - // Decide if we are going to emit telemetry about video low power on this commit. + // Decide if we are going to emit telemetry about video low power on this + // commit. static const int32_t TELEMETRY_COMMIT_PERIOD = StaticPrefs::gfx_core_animation_low_power_telemetry_frames_AtStartup(); mTelemetryCommitCount = (mTelemetryCommitCount + 1) % TELEMETRY_COMMIT_PERIOD; @@ -324,11 +351,12 @@ bool NativeLayerRootCA::CommitToScreen() { UniquePtr NativeLayerRootCA::CreateSnapshotter() { MutexAutoLock lock(mMutex); - MOZ_RELEASE_ASSERT( - !mWeakSnapshotter, - "No NativeLayerRootSnapshotter for this NativeLayerRoot should exist when this is called"); + MOZ_RELEASE_ASSERT(!mWeakSnapshotter, + "No NativeLayerRootSnapshotter for this NativeLayerRoot " + "should exist when this is called"); - auto cr = NativeLayerRootSnapshotterCA::Create(this, mOffscreenRepresentation.mRootCALayer); + auto cr = NativeLayerRootSnapshotterCA::Create( + this, mOffscreenRepresentation.mRootCALayer); if (cr) { mWeakSnapshotter = cr.get(); } @@ -344,7 +372,8 @@ void NativeLayerRootCA::OnNativeLayerRootSnapshotterDestroyed( void NativeLayerRootCA::CommitOffscreen() { MutexAutoLock lock(mMutex); - mOffscreenRepresentation.Commit(WhichRepresentation::OFFSCREEN, mSublayers, mWindowIsFullscreen); + mOffscreenRepresentation.Commit(WhichRepresentation::OFFSCREEN, mSublayers, + mWindowIsFullscreen); } template @@ -358,8 +387,8 @@ NativeLayerRootCA::Representation::Representation(CALayer* aRootCALayer) NativeLayerRootCA::Representation::~Representation() { if (mMutatedLayerStructure) { - // Clear the root layer's sublayers. At this point the window is usually closed, so this - // transaction does not cause any screen updates. + // Clear the root layer's sublayers. At this point the window is usually + // closed, so this transaction does not cause any screen updates. AutoCATransaction transaction; mRootCALayer.sublayers = @[]; } @@ -367,17 +396,20 @@ NativeLayerRootCA::Representation::~Representation() { [mRootCALayer release]; } -void NativeLayerRootCA::Representation::Commit(WhichRepresentation aRepresentation, - const nsTArray>& aSublayers, - bool aWindowIsFullscreen) { +void NativeLayerRootCA::Representation::Commit( + WhichRepresentation aRepresentation, + const nsTArray>& aSublayers, + bool aWindowIsFullscreen) { bool mustRebuild = mMutatedLayerStructure; if (!mustRebuild) { // Check which type of update we need to do, if any. NativeLayerCA::UpdateType updateRequired = NativeLayerCA::UpdateType::None; for (auto layer : aSublayers) { - // Use the ordering of our UpdateType enums to build a maximal update type. - updateRequired = std::max(updateRequired, layer->HasUpdate(aRepresentation)); + // Use the ordering of our UpdateType enums to build a maximal update + // type. + updateRequired = + std::max(updateRequired, layer->HasUpdate(aRepresentation)); if (updateRequired == NativeLayerCA::UpdateType::All) { break; } @@ -390,8 +422,10 @@ void NativeLayerRootCA::Representation::Commit(WhichRepresentation aRepresentati if (updateRequired == NativeLayerCA::UpdateType::OnlyVideo) { bool allUpdatesSucceeded = std::all_of( - aSublayers.begin(), aSublayers.end(), [=](const RefPtr& layer) { - return layer->ApplyChanges(aRepresentation, NativeLayerCA::UpdateType::OnlyVideo); + aSublayers.begin(), aSublayers.end(), + [=](const RefPtr& layer) { + return layer->ApplyChanges(aRepresentation, + NativeLayerCA::UpdateType::OnlyVideo); }); if (allUpdatesSucceeded) { @@ -401,8 +435,9 @@ void NativeLayerRootCA::Representation::Commit(WhichRepresentation aRepresentati } } - // We're going to do a full update now, which requires a transaction. Update all of the - // sublayers. Afterwards, only continue processing the sublayers which have an extent. + // We're going to do a full update now, which requires a transaction. Update + // all of the sublayers. Afterwards, only continue processing the sublayers + // which have an extent. AutoCATransaction transaction; nsTArray sublayersWithExtent; for (auto layer : aSublayers) { @@ -420,16 +455,19 @@ void NativeLayerRootCA::Representation::Commit(WhichRepresentation aRepresentati layer->SetHasExtent(false); } - // One other reason we may need to rebuild is if the caLayer is not part of the - // root layer's sublayers. This might happen if the caLayer was rebuilt. - // We construct this check in a way that maximizes the boolean short-circuit, - // because we don't want to call containsObject unless absolutely necessary. - mustRebuild = mustRebuild || ![mRootCALayer.sublayers containsObject:caLayer]; + // One other reason we may need to rebuild is if the caLayer is not part of + // the root layer's sublayers. This might happen if the caLayer was rebuilt. + // We construct this check in a way that maximizes the boolean + // short-circuit, because we don't want to call containsObject unless + // absolutely necessary. + mustRebuild = + mustRebuild || ![mRootCALayer.sublayers containsObject:caLayer]; } if (mustRebuild) { uint32_t sublayersCount = sublayersWithExtent.Length(); - NSMutableArray* sublayers = [NSMutableArray arrayWithCapacity:sublayersCount]; + NSMutableArray* sublayers = + [NSMutableArray arrayWithCapacity:sublayersCount]; for (auto layer : sublayersWithExtent) { [sublayers addObject:layer->UnderlyingCALayer(aRepresentation)]; } @@ -439,28 +477,31 @@ void NativeLayerRootCA::Representation::Commit(WhichRepresentation aRepresentati mMutatedLayerStructure = false; } -/* static */ UniquePtr NativeLayerRootSnapshotterCA::Create( - NativeLayerRootCA* aLayerRoot, CALayer* aRootCALayer) { +/* static */ UniquePtr +NativeLayerRootSnapshotterCA::Create(NativeLayerRootCA* aLayerRoot, + CALayer* aRootCALayer) { if (NS_IsMainThread()) { // Disallow creating snapshotters on the main thread. - // On the main thread, any explicit CATransaction / NSAnimationContext is nested within a global - // implicit transaction. This makes it impossible to apply CALayer mutations synchronously such - // that they become visible to CARenderer. As a result, the snapshotter would not capture - // the right output on the main thread. + // On the main thread, any explicit CATransaction / NSAnimationContext is + // nested within a global implicit transaction. This makes it impossible to + // apply CALayer mutations synchronously such that they become visible to + // CARenderer. As a result, the snapshotter would not capture the right + // output on the main thread. return nullptr; } nsCString failureUnused; - RefPtr gl = - gl::GLContextProvider::CreateHeadless({gl::CreateContextFlags::ALLOW_OFFLINE_RENDERER | - gl::CreateContextFlags::REQUIRE_COMPAT_PROFILE}, - &failureUnused); + RefPtr gl = gl::GLContextProvider::CreateHeadless( + {gl::CreateContextFlags::ALLOW_OFFLINE_RENDERER | + gl::CreateContextFlags::REQUIRE_COMPAT_PROFILE}, + &failureUnused); if (!gl) { return nullptr; } return UniquePtr( - new NativeLayerRootSnapshotterCA(aLayerRoot, std::move(gl), aRootCALayer)); + new NativeLayerRootSnapshotterCA(aLayerRoot, std::move(gl), + aRootCALayer)); } void NativeLayerRootCA::DumpLayerTreeToFile(const char* aPath) { @@ -554,9 +595,9 @@ VideoLowPowerType NativeLayerRootCA::CheckVideoLowPower() { return VideoLowPowerType::NotVideo; } - // Most importantly, check if the window is fullscreen. If the user is watching - // video in a window, then all of the other enums are irrelevant to achieving - // the low power mode. + // Most importantly, check if the window is fullscreen. If the user is + // watching video in a window, then all of the other enums are irrelevant to + // achieving the low power mode. if (!mWindowIsFullscreen) { return VideoLowPowerType::FailWindowed; } @@ -570,7 +611,8 @@ VideoLowPowerType NativeLayerRootCA::CheckVideoLowPower() { } if (!secondCALayer || !IsCGColorOpaqueBlack(secondCALayer.backgroundColor) || - !CGRectContainsRect(secondCALayer.frame, secondCALayer.superlayer.bounds)) { + !CGRectContainsRect(secondCALayer.frame, + secondCALayer.superlayer.bounds)) { return VideoLowPowerType::FailBacking; } @@ -592,15 +634,17 @@ VideoLowPowerType NativeLayerRootCA::CheckVideoLowPower() { MacIOSurface* macIOSurface = topLayer->mTextureHost->GetSurface(); CFTypeRefPtr surface = macIOSurface->GetIOSurfaceRef(); OSType pixelFormat = IOSurfaceGetPixelFormat(surface.get()); - MOZ_ASSERT(!(pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange || - pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange || - pixelFormat == kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange || - pixelFormat == kCVPixelFormatType_420YpCbCr10BiPlanarFullRange)); + MOZ_ASSERT( + !(pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange || + pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange || + pixelFormat == kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange || + pixelFormat == kCVPixelFormatType_420YpCbCr10BiPlanarFullRange)); #endif return VideoLowPowerType::FailSurface; } - AVSampleBufferDisplayLayer* topVideoLayer = (AVSampleBufferDisplayLayer*)topContentCALayer; + AVSampleBufferDisplayLayer* topVideoLayer = + (AVSampleBufferDisplayLayer*)topContentCALayer; if (topVideoLayer.status != AVQueuedSampleBufferRenderingStatusRendering) { return VideoLowPowerType::FailEnqueue; } @@ -609,13 +653,14 @@ VideoLowPowerType NativeLayerRootCA::CheckVideoLowPower() { return VideoLowPowerType::LowPower; } -NativeLayerRootSnapshotterCA::NativeLayerRootSnapshotterCA(NativeLayerRootCA* aLayerRoot, - RefPtr&& aGL, - CALayer* aRootCALayer) +NativeLayerRootSnapshotterCA::NativeLayerRootSnapshotterCA( + NativeLayerRootCA* aLayerRoot, RefPtr&& aGL, + CALayer* aRootCALayer) : mLayerRoot(aLayerRoot), mGL(aGL) { AutoCATransaction transaction; - mRenderer = [[CARenderer rendererWithCGLContext:gl::GLContextCGL::Cast(mGL)->GetCGLContext() - options:nil] retain]; + mRenderer = [[CARenderer + rendererWithCGLContext:gl::GLContextCGL::Cast(mGL)->GetCGLContext() + options:nil] retain]; mRenderer.layer = aRootCALayer; } @@ -634,11 +679,12 @@ void NativeLayerRootSnapshotterCA::UpdateSnapshot(const IntSize& aSize) { CGRect bounds = CGRectMake(0, 0, aSize.width, aSize.height); { - // Set the correct bounds and scale on the renderer and its root layer. CARenderer always - // renders at unit scale, i.e. the coordinates on the root layer must map 1:1 to render target - // pixels. But the coordinates on our content layers are in "points", where 1 point maps to 2 - // device pixels on HiDPI. So in order to render at the full device pixel resolution, we set a - // scale transform on the root offscreen layer. + // Set the correct bounds and scale on the renderer and its root layer. + // CARenderer always renders at unit scale, i.e. the coordinates on the root + // layer must map 1:1 to render target pixels. But the coordinates on our + // content layers are in "points", where 1 point maps to 2 device pixels on + // HiDPI. So in order to render at the full device pixel resolution, we set + // a scale transform on the root offscreen layer. AutoCATransaction transaction; mRenderer.layer.bounds = bounds; float scale = mLayerRoot->BackingScale(); @@ -664,9 +710,9 @@ void NativeLayerRootSnapshotterCA::UpdateSnapshot(const IntSize& aSize) { const gl::ScopedBindFramebuffer bindFB(mGL, mSnapshot->FB().mFB); mGL->fViewport(0.0, 0.0, aSize.width, aSize.height); - // These legacy OpenGL function calls are part of CARenderer's API contract, see CARenderer.h. - // The size passed to glOrtho must be the device pixel size of the render target, otherwise - // CARenderer will produce incorrect results. + // These legacy OpenGL function calls are part of CARenderer's API contract, + // see CARenderer.h. The size passed to glOrtho must be the device pixel size + // of the render target, otherwise CARenderer will produce incorrect results. glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, aSize.width, 0.0, aSize.height, -1, 1); @@ -677,30 +723,33 @@ void NativeLayerRootSnapshotterCA::UpdateSnapshot(const IntSize& aSize) { [mRenderer addUpdateRect:bounds]; } if (!CGRectIsEmpty([mRenderer updateBounds])) { - // CARenderer assumes the layer tree is opaque. It only ever paints over existing content, it - // never erases anything. However, our layer tree is not necessarily opaque. So we manually - // erase the area that's going to be redrawn. This ensures correct rendering in the transparent - // areas. + // CARenderer assumes the layer tree is opaque. It only ever paints over + // existing content, it never erases anything. However, our layer tree is + // not necessarily opaque. So we manually erase the area that's going to be + // redrawn. This ensures correct rendering in the transparent areas. // - // Since we erase the bounds of the update area, this will erase more than necessary if the - // update area is not a single rectangle. Unfortunately we cannot get the precise update region - // from CARenderer, we can only get the bounds. + // Since we erase the bounds of the update area, this will erase more than + // necessary if the update area is not a single rectangle. Unfortunately we + // cannot get the precise update region from CARenderer, we can only get the + // bounds. CGRect updateBounds = [mRenderer updateBounds]; gl::ScopedGLState scopedScissorTestState(mGL, LOCAL_GL_SCISSOR_TEST, true); - gl::ScopedScissorRect scissor(mGL, updateBounds.origin.x, updateBounds.origin.y, - updateBounds.size.width, updateBounds.size.height); + gl::ScopedScissorRect scissor( + mGL, updateBounds.origin.x, updateBounds.origin.y, + updateBounds.size.width, updateBounds.size.height); mGL->fClearColor(0.0, 0.0, 0.0, 0.0); mGL->fClear(LOCAL_GL_COLOR_BUFFER_BIT); - // We erased the update region's bounds. Make sure the entire update bounds get repainted. + // We erased the update region's bounds. Make sure the entire update bounds + // get repainted. [mRenderer addUpdateRect:updateBounds]; } [mRenderer render]; [mRenderer endFrame]; } -bool NativeLayerRootSnapshotterCA::ReadbackPixels(const IntSize& aReadbackSize, - SurfaceFormat aReadbackFormat, - const Range& aReadbackBuffer) { +bool NativeLayerRootSnapshotterCA::ReadbackPixels( + const IntSize& aReadbackSize, SurfaceFormat aReadbackFormat, + const Range& aReadbackBuffer) { if (aReadbackFormat != SurfaceFormat::B8G8R8A8) { return false; } @@ -712,8 +761,8 @@ bool NativeLayerRootSnapshotterCA::ReadbackPixels(const IntSize& aReadbackSize, const gl::ScopedBindFramebuffer bindFB(mGL, mSnapshot->FB().mFB); gl::ScopedPackState safePackState(mGL); - mGL->fReadPixels(0.0f, 0.0f, aReadbackSize.width, aReadbackSize.height, LOCAL_GL_BGRA, - LOCAL_GL_UNSIGNED_BYTE, &aReadbackBuffer[0]); + mGL->fReadPixels(0.0f, 0.0f, aReadbackSize.width, aReadbackSize.height, + LOCAL_GL_BGRA, LOCAL_GL_UNSIGNED_BYTE, &aReadbackBuffer[0]); return true; } @@ -724,7 +773,8 @@ NativeLayerRootSnapshotterCA::CreateDownscaleTarget(const IntSize& aSize) { if (!fb) { return nullptr; } - RefPtr dt = new DownscaleTargetNLRS(mGL, std::move(fb)); + RefPtr dt = + new DownscaleTargetNLRS(mGL, std::move(fb)); return dt.forget(); } @@ -737,7 +787,8 @@ NativeLayerRootSnapshotterCA::CreateAsyncReadbackBuffer(const IntSize& aSize) { gl::ScopedPackState scopedPackState(mGL); mGL->fBindBuffer(LOCAL_GL_PIXEL_PACK_BUFFER, bufferHandle); mGL->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, 1); - mGL->fBufferData(LOCAL_GL_PIXEL_PACK_BUFFER, bufferByteCount, nullptr, LOCAL_GL_STREAM_READ); + mGL->fBufferData(LOCAL_GL_PIXEL_PACK_BUFFER, bufferByteCount, nullptr, + LOCAL_GL_STREAM_READ); return MakeAndAddRef(mGL, aSize, bufferHandle); } @@ -747,14 +798,18 @@ NativeLayerCA::NativeLayerCA(const IntSize& aSize, bool aIsOpaque, mSurfacePoolHandle(aSurfacePoolHandle), mSize(aSize), mIsOpaque(aIsOpaque) { - MOZ_RELEASE_ASSERT(mSurfacePoolHandle, "Need a non-null surface pool handle."); + MOZ_RELEASE_ASSERT(mSurfacePoolHandle, + "Need a non-null surface pool handle."); } NativeLayerCA::NativeLayerCA(bool aIsOpaque) - : mMutex("NativeLayerCA"), mSurfacePoolHandle(nullptr), mIsOpaque(aIsOpaque) { + : mMutex("NativeLayerCA"), + mSurfacePoolHandle(nullptr), + mIsOpaque(aIsOpaque) { #ifdef NIGHTLY_BUILD if (StaticPrefs::gfx_core_animation_specialize_video_log()) { - NSLog(@"VIDEO_LOG: NativeLayerCA: %p is being created to host video, which will force a video " + NSLog(@"VIDEO_LOG: NativeLayerCA: %p is being created to host video, which " + @"will force a video " @"layer rebuild.", this); } @@ -770,15 +825,20 @@ CGColorRef CGColorCreateForDeviceColor(gfx::DeviceColor aColor) { } NativeLayerCA::NativeLayerCA(gfx::DeviceColor aColor) - : mMutex("NativeLayerCA"), mSurfacePoolHandle(nullptr), mIsOpaque(aColor.a >= 1.0f) { + : mMutex("NativeLayerCA"), + mSurfacePoolHandle(nullptr), + mIsOpaque(aColor.a >= 1.0f) { MOZ_ASSERT(aColor.a > 0.0f, "Can't handle a fully transparent backdrop."); mColor.AssignUnderCreateRule(CGColorCreateForDeviceColor(aColor)); } NativeLayerCA::~NativeLayerCA() { #ifdef NIGHTLY_BUILD - if (mHasEverAttachExternalImage && StaticPrefs::gfx_core_animation_specialize_video_log()) { - NSLog(@"VIDEO_LOG: ~NativeLayerCA: %p is being destroyed after hosting video.", this); + if (mHasEverAttachExternalImage && + StaticPrefs::gfx_core_animation_specialize_video_log()) { + NSLog(@"VIDEO_LOG: ~NativeLayerCA: %p is being destroyed after hosting " + @"video.", + this); } #endif if (mInProgressLockedIOSurface) { @@ -802,10 +862,12 @@ void NativeLayerCA::AttachExternalImage(wr::RenderTextureHost* aExternalImage) { #ifdef NIGHTLY_BUILD mHasEverAttachExternalImage = true; - MOZ_RELEASE_ASSERT(!mHasEverNotifySurfaceReady, "Shouldn't change layer type to external."); + MOZ_RELEASE_ASSERT(!mHasEverNotifySurfaceReady, + "Shouldn't change layer type to external."); #endif - wr::RenderMacIOSurfaceTextureHost* texture = aExternalImage->AsRenderMacIOSurfaceTextureHost(); + wr::RenderMacIOSurfaceTextureHost* texture = + aExternalImage->AsRenderMacIOSurfaceTextureHost(); MOZ_ASSERT(texture || aExternalImage->IsWrappingAsyncRemoteTexture()); mTextureHost = texture; if (!mTextureHost) { @@ -823,8 +885,11 @@ void NativeLayerCA::AttachExternalImage(wr::RenderTextureHost* aExternalImage) { mSpecializeVideo = ShouldSpecializeVideo(lock); bool changedSpecializeVideo = (mSpecializeVideo != oldSpecializeVideo); #ifdef NIGHTLY_BUILD - if (changedSpecializeVideo && StaticPrefs::gfx_core_animation_specialize_video_log()) { - NSLog(@"VIDEO_LOG: AttachExternalImage: %p is forcing a video layer rebuild.", this); + if (changedSpecializeVideo && + StaticPrefs::gfx_core_animation_specialize_video_log()) { + NSLog( + @"VIDEO_LOG: AttachExternalImage: %p is forcing a video layer rebuild.", + this); } #endif @@ -916,11 +981,14 @@ void NativeLayerCA::SetRootWindowIsFullscreen(bool aFullscreen) { if (changedSpecializeVideo) { #ifdef NIGHTLY_BUILD if (StaticPrefs::gfx_core_animation_specialize_video_log()) { - NSLog(@"VIDEO_LOG: SetRootWindowIsFullscreen: %p is forcing a video layer rebuild.", this); + NSLog(@"VIDEO_LOG: SetRootWindowIsFullscreen: %p is forcing a video " + @"layer rebuild.", + this); } #endif - ForAllRepresentations([&](Representation& r) { r.mMutatedSpecializeVideo = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedSpecializeVideo = true; }); } } @@ -929,7 +997,8 @@ void NativeLayerCA::SetSurfaceIsFlipped(bool aIsFlipped) { if (aIsFlipped != mSurfaceIsFlipped) { mSurfaceIsFlipped = aIsFlipped; - ForAllRepresentations([&](Representation& r) { r.mMutatedSurfaceIsFlipped = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedSurfaceIsFlipped = true; }); } } @@ -948,7 +1017,8 @@ void NativeLayerCA::SetPosition(const IntPoint& aPosition) { if (aPosition != mPosition) { mPosition = aPosition; - ForAllRepresentations([&](Representation& r) { r.mMutatedPosition = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedPosition = true; }); } } @@ -963,7 +1033,8 @@ void NativeLayerCA::SetTransform(const Matrix4x4& aTransform) { if (aTransform != mTransform) { mTransform = aTransform; - ForAllRepresentations([&](Representation& r) { r.mMutatedTransform = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedTransform = true; }); } } @@ -972,7 +1043,8 @@ void NativeLayerCA::SetSamplingFilter(gfx::SamplingFilter aSamplingFilter) { if (aSamplingFilter != mSamplingFilter) { mSamplingFilter = aSamplingFilter; - ForAllRepresentations([&](Representation& r) { r.mMutatedSamplingFilter = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedSamplingFilter = true; }); } } @@ -991,7 +1063,8 @@ void NativeLayerCA::SetBackingScale(float aBackingScale) { if (aBackingScale != mBackingScale) { mBackingScale = aBackingScale; - ForAllRepresentations([&](Representation& r) { r.mMutatedBackingScale = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedBackingScale = true; }); } } @@ -1005,7 +1078,8 @@ void NativeLayerCA::SetClipRect(const Maybe& aClipRect) { if (aClipRect != mClipRect) { mClipRect = aClipRect; - ForAllRepresentations([&](Representation& r) { r.mMutatedClipRect = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedClipRect = true; }); } } @@ -1017,8 +1091,8 @@ Maybe NativeLayerCA::ClipRect() { void NativeLayerCA::DumpLayer(std::ostream& aOutputStream) { MutexAutoLock lock(mMutex); - Maybe scaledClipRect = - CalculateClipGeometry(mSize, mPosition, mTransform, mDisplayRect, mClipRect, mBackingScale); + Maybe scaledClipRect = CalculateClipGeometry( + mSize, mPosition, mTransform, mDisplayRect, mClipRect, mBackingScale); CGRect useClipRect; if (scaledClipRect.isSome()) { @@ -1040,8 +1114,9 @@ void NativeLayerCA::DumpLayer(std::ostream& aOutputStream) { if (mColor) { const CGFloat* components = CGColorGetComponents(mColor.get()); - aOutputStream << "background: rgb(" << components[0] * 255.0f << " " << components[1] * 255.0f - << " " << components[2] * 255.0f << "); opacity: " << components[3] << "; "; + aOutputStream << "background: rgb(" << components[0] * 255.0f << " " + << components[1] * 255.0f << " " << components[2] * 255.0f + << "); opacity: " << components[3] << "; "; // That's all we need for color layers. We don't need to specify an image. aOutputStream << "\"/>\n"; @@ -1073,11 +1148,14 @@ void NativeLayerCA::DumpLayer(std::ostream& aOutputStream) { const auto& m = transform; aOutputStream << "transform-origin: top left; "; aOutputStream << "transform: matrix3d("; - aOutputStream << m._11 << ", " << m._12 << ", " << m._13 << ", " << m._14 << ", "; - aOutputStream << m._21 << ", " << m._22 << ", " << m._23 << ", " << m._24 << ", "; - aOutputStream << m._31 << ", " << m._32 << ", " << m._33 << ", " << m._34 << ", "; - aOutputStream << m._41 / mBackingScale << ", " << m._42 / mBackingScale << ", " << m._43 << ", " - << m._44; + aOutputStream << m._11 << ", " << m._12 << ", " << m._13 << ", " << m._14 + << ", "; + aOutputStream << m._21 << ", " << m._22 << ", " << m._23 << ", " << m._24 + << ", "; + aOutputStream << m._31 << ", " << m._32 << ", " << m._33 << ", " << m._34 + << ", "; + aOutputStream << m._41 / mBackingScale << ", " << m._42 / mBackingScale + << ", " << m._43 << ", " << m._44; aOutputStream << "); "; } aOutputStream << "\" "; @@ -1085,8 +1163,8 @@ void NativeLayerCA::DumpLayer(std::ostream& aOutputStream) { CFTypeRefPtr surface; if (mFrontSurface) { surface = mFrontSurface->mSurface; - aOutputStream << "alt=\"regular surface 0x" << std::hex << int(IOSurfaceGetID(surface.get())) - << "\" "; + aOutputStream << "alt=\"regular surface 0x" << std::hex + << int(IOSurfaceGetID(surface.get())) << "\" "; } else if (mTextureHost) { surface = mTextureHost->GetSurface()->GetIOSurfaceRef(); aOutputStream << "alt=\"TextureHost surface 0x" << std::hex @@ -1098,17 +1176,21 @@ void NativeLayerCA::DumpLayer(std::ostream& aOutputStream) { aOutputStream << "src=\""; if (surface) { - // Attempt to render the surface as a PNG. Skia can do this for RGB surfaces. + // Attempt to render the surface as a PNG. Skia can do this for RGB + // surfaces. RefPtr surf = new MacIOSurface(surface); surf->Lock(true); SurfaceFormat format = surf->GetFormat(); - if (format == SurfaceFormat::B8G8R8A8 || format == SurfaceFormat::B8G8R8X8) { - RefPtr dt = surf->GetAsDrawTargetLocked(gfx::BackendType::SKIA); + if (format == SurfaceFormat::B8G8R8A8 || + format == SurfaceFormat::B8G8R8X8) { + RefPtr dt = + surf->GetAsDrawTargetLocked(gfx::BackendType::SKIA); if (dt) { RefPtr sourceSurf = dt->Snapshot(); nsCString dataUrl; - gfxUtils::EncodeSourceSurface(sourceSurf, ImageType::PNG, u""_ns, gfxUtils::eDataURIEncode, - nullptr, &dataUrl); + gfxUtils::EncodeSourceSurface(sourceSurf, ImageType::PNG, u""_ns, + gfxUtils::eDataURIEncode, nullptr, + &dataUrl); aOutputStream << dataUrl.get(); } } @@ -1142,8 +1224,8 @@ NativeLayerCA::Representation::~Representation() { [mWrappingCALayer release]; } -void NativeLayerCA::InvalidateRegionThroughoutSwapchain(const MutexAutoLock& aProofOfLock, - const IntRegion& aRegion) { +void NativeLayerCA::InvalidateRegionThroughoutSwapchain( + const MutexAutoLock& aProofOfLock, const IntRegion& aRegion) { IntRegion r = aRegion; if (mInProgressSurface) { mInProgressSurface->mInvalidRegion.OrWith(r); @@ -1158,20 +1240,24 @@ void NativeLayerCA::InvalidateRegionThroughoutSwapchain(const MutexAutoLock& aPr bool NativeLayerCA::NextSurface(const MutexAutoLock& aProofOfLock) { if (mSize.IsEmpty()) { - gfxCriticalError() << "NextSurface returning false because of invalid mSize (" << mSize.width - << ", " << mSize.height << ")."; + gfxCriticalError() + << "NextSurface returning false because of invalid mSize (" + << mSize.width << ", " << mSize.height << ")."; return false; } - MOZ_RELEASE_ASSERT( - !mInProgressSurface, - "ERROR: Do not call NextSurface twice in sequence. Call NotifySurfaceReady before the " - "next call to NextSurface."); + MOZ_RELEASE_ASSERT(!mInProgressSurface, + "ERROR: Do not call NextSurface twice in sequence. Call " + "NotifySurfaceReady before the " + "next call to NextSurface."); - Maybe surf = GetUnusedSurfaceAndCleanUp(aProofOfLock); + Maybe surf = + GetUnusedSurfaceAndCleanUp(aProofOfLock); if (!surf) { - CFTypeRefPtr newSurf = mSurfacePoolHandle->ObtainSurfaceFromPool(mSize); - MOZ_RELEASE_ASSERT(newSurf, "NextSurface IOSurfaceCreate failed to create the surface."); + CFTypeRefPtr newSurf = + mSurfacePoolHandle->ObtainSurfaceFromPool(mSize); + MOZ_RELEASE_ASSERT( + newSurf, "NextSurface IOSurfaceCreate failed to create the surface."); surf = Some(SurfaceWithInvalidRegion{newSurf, IntRect({}, mSize)}); } @@ -1182,7 +1268,8 @@ bool NativeLayerCA::NextSurface(const MutexAutoLock& aProofOfLock) { template void NativeLayerCA::HandlePartialUpdate(const MutexAutoLock& aProofOfLock, - const IntRect& aDisplayRect, const IntRegion& aUpdateRegion, + const IntRect& aDisplayRect, + const IntRegion& aUpdateRegion, F&& aCopyFn) { MOZ_RELEASE_ASSERT(IntRect({}, mSize).Contains(aUpdateRegion.GetBounds()), "The update region should be within the surface bounds."); @@ -1196,7 +1283,8 @@ void NativeLayerCA::HandlePartialUpdate(const MutexAutoLock& aProofOfLock, mInProgressDisplayRect = Some(aDisplayRect); if (mFrontSurface) { - // Copy not-overwritten valid content from mFrontSurface so that valid content never gets lost. + // Copy not-overwritten valid content from mFrontSurface so that valid + // content never gets lost. gfx::IntRegion copyRegion; copyRegion.Sub(mInProgressSurface->mInvalidRegion, aUpdateRegion); copyRegion.SubOut(mFrontSurface->mInvalidRegion); @@ -1211,9 +1299,9 @@ void NativeLayerCA::HandlePartialUpdate(const MutexAutoLock& aProofOfLock, InvalidateRegionThroughoutSwapchain(aProofOfLock, aUpdateRegion); } -RefPtr NativeLayerCA::NextSurfaceAsDrawTarget(const IntRect& aDisplayRect, - const IntRegion& aUpdateRegion, - gfx::BackendType aBackendType) { +RefPtr NativeLayerCA::NextSurfaceAsDrawTarget( + const IntRect& aDisplayRect, const IntRegion& aUpdateRegion, + gfx::BackendType aBackendType) { MutexAutoLock lock(mMutex); if (!NextSurface(lock)) { return nullptr; @@ -1221,15 +1309,18 @@ RefPtr NativeLayerCA::NextSurfaceAsDrawTarget(const IntRect& aD mInProgressLockedIOSurface = new MacIOSurface(mInProgressSurface->mSurface); mInProgressLockedIOSurface->Lock(false); - RefPtr dt = mInProgressLockedIOSurface->GetAsDrawTargetLocked(aBackendType); + RefPtr dt = + mInProgressLockedIOSurface->GetAsDrawTargetLocked(aBackendType); HandlePartialUpdate( lock, aDisplayRect, aUpdateRegion, - [&](CFTypeRefPtr validSource, const gfx::IntRegion& copyRegion) { + [&](CFTypeRefPtr validSource, + const gfx::IntRegion& copyRegion) { RefPtr source = new MacIOSurface(validSource); source->Lock(true); { - RefPtr sourceDT = source->GetAsDrawTargetLocked(aBackendType); + RefPtr sourceDT = + source->GetAsDrawTargetLocked(aBackendType); RefPtr sourceSurface = sourceDT->Snapshot(); for (auto iter = copyRegion.RectIter(); !iter.Done(); iter.Next()) { @@ -1243,32 +1334,36 @@ RefPtr NativeLayerCA::NextSurfaceAsDrawTarget(const IntRect& aD return dt; } -Maybe NativeLayerCA::NextSurfaceAsFramebuffer(const IntRect& aDisplayRect, - const IntRegion& aUpdateRegion, - bool aNeedsDepth) { +Maybe NativeLayerCA::NextSurfaceAsFramebuffer( + const IntRect& aDisplayRect, const IntRegion& aUpdateRegion, + bool aNeedsDepth) { MutexAutoLock lock(mMutex); - MOZ_RELEASE_ASSERT(NextSurface(lock), "NextSurfaceAsFramebuffer needs a surface."); + MOZ_RELEASE_ASSERT(NextSurface(lock), + "NextSurfaceAsFramebuffer needs a surface."); - Maybe fbo = - mSurfacePoolHandle->GetFramebufferForSurface(mInProgressSurface->mSurface, aNeedsDepth); + Maybe fbo = mSurfacePoolHandle->GetFramebufferForSurface( + mInProgressSurface->mSurface, aNeedsDepth); MOZ_RELEASE_ASSERT(fbo, "GetFramebufferForSurface failed."); HandlePartialUpdate( lock, aDisplayRect, aUpdateRegion, - [&](CFTypeRefPtr validSource, const gfx::IntRegion& copyRegion) { + [&](CFTypeRefPtr validSource, + const gfx::IntRegion& copyRegion) { // Copy copyRegion from validSource to fbo. MOZ_RELEASE_ASSERT(mSurfacePoolHandle->gl()); mSurfacePoolHandle->gl()->MakeCurrent(); - Maybe sourceFBO = mSurfacePoolHandle->GetFramebufferForSurface(validSource, false); - MOZ_RELEASE_ASSERT(sourceFBO, - "GetFramebufferForSurface failed during HandlePartialUpdate."); + Maybe sourceFBO = + mSurfacePoolHandle->GetFramebufferForSurface(validSource, false); + MOZ_RELEASE_ASSERT( + sourceFBO, + "GetFramebufferForSurface failed during HandlePartialUpdate."); for (auto iter = copyRegion.RectIter(); !iter.Done(); iter.Next()) { gfx::IntRect r = iter.Get(); if (mSurfaceIsFlipped) { r.y = mSize.height - r.YMost(); } - mSurfacePoolHandle->gl()->BlitHelper()->BlitFramebufferToFramebuffer(*sourceFBO, *fbo, r, - r, LOCAL_GL_NEAREST); + mSurfacePoolHandle->gl()->BlitHelper()->BlitFramebufferToFramebuffer( + *sourceFBO, *fbo, r, r, LOCAL_GL_NEAREST); } }); @@ -1280,11 +1375,13 @@ void NativeLayerCA::NotifySurfaceReady() { #ifdef NIGHTLY_BUILD mHasEverNotifySurfaceReady = true; - MOZ_RELEASE_ASSERT(!mHasEverAttachExternalImage, "Shouldn't change layer type to drawn."); + MOZ_RELEASE_ASSERT(!mHasEverAttachExternalImage, + "Shouldn't change layer type to drawn."); #endif - MOZ_RELEASE_ASSERT(mInProgressSurface, - "NotifySurfaceReady called without preceding call to NextSurface"); + MOZ_RELEASE_ASSERT( + mInProgressSurface, + "NotifySurfaceReady called without preceding call to NextSurface"); if (mInProgressLockedIOSurface) { mInProgressLockedIOSurface->Unlock(false); @@ -1301,12 +1398,14 @@ void NativeLayerCA::NotifySurfaceReady() { mFrontSurface = std::move(mInProgressSurface); mFrontSurface->mInvalidRegion.SubOut(mInProgressUpdateRegion.extract()); - ForAllRepresentations([&](Representation& r) { r.mMutatedFrontSurface = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedFrontSurface = true; }); MOZ_RELEASE_ASSERT(mInProgressDisplayRect); if (!mDisplayRect.IsEqualInterior(*mInProgressDisplayRect)) { mDisplayRect = *mInProgressDisplayRect; - ForAllRepresentations([&](Representation& r) { r.mMutatedDisplayRect = true; }); + ForAllRepresentations( + [&](Representation& r) { r.mMutatedDisplayRect = true; }); } mInProgressDisplayRect = Nothing(); } @@ -1336,32 +1435,37 @@ void NativeLayerCA::ForAllRepresentations(F aFn) { aFn(mOffscreenRepresentation); } -NativeLayerCA::UpdateType NativeLayerCA::HasUpdate(WhichRepresentation aRepresentation) { +NativeLayerCA::UpdateType NativeLayerCA::HasUpdate( + WhichRepresentation aRepresentation) { MutexAutoLock lock(mMutex); return GetRepresentation(aRepresentation).HasUpdate(IsVideoAndLocked(lock)); } /* static */ Maybe NativeLayerCA::CalculateClipGeometry( - const gfx::IntSize& aSize, const gfx::IntPoint& aPosition, const gfx::Matrix4x4& aTransform, - const gfx::IntRect& aDisplayRect, const Maybe& aClipRect, float aBackingScale) { + const gfx::IntSize& aSize, const gfx::IntPoint& aPosition, + const gfx::Matrix4x4& aTransform, const gfx::IntRect& aDisplayRect, + const Maybe& aClipRect, float aBackingScale) { Maybe clipFromDisplayRect; if (!aDisplayRect.IsEqualInterior(IntRect({}, aSize))) { - // When the display rect is a subset of the layer, then we want to guarantee that no - // pixels outside that rect are sampled, since they might be uninitialized. - // Transforming the display rect into a post-transform clip only maintains this if - // it's an integer translation, which is all we support for this case currently. + // When the display rect is a subset of the layer, then we want to guarantee + // that no pixels outside that rect are sampled, since they might be + // uninitialized. Transforming the display rect into a post-transform clip + // only maintains this if it's an integer translation, which is all we + // support for this case currently. MOZ_ASSERT(aTransform.Is2DIntegerTranslation()); - clipFromDisplayRect = - Some(RoundedToInt(aTransform.TransformBounds(IntRectToRect(aDisplayRect + aPosition)))); + clipFromDisplayRect = Some(RoundedToInt( + aTransform.TransformBounds(IntRectToRect(aDisplayRect + aPosition)))); } - Maybe effectiveClip = IntersectMaybeRects(aClipRect, clipFromDisplayRect); + Maybe effectiveClip = + IntersectMaybeRects(aClipRect, clipFromDisplayRect); if (!effectiveClip) { return Nothing(); } - return Some(CGRectMake(effectiveClip->X() / aBackingScale, effectiveClip->Y() / aBackingScale, + return Some(CGRectMake(effectiveClip->X() / aBackingScale, + effectiveClip->Y() / aBackingScale, effectiveClip->Width() / aBackingScale, effectiveClip->Height() / aBackingScale)); } @@ -1376,9 +1480,10 @@ bool NativeLayerCA::ApplyChanges(WhichRepresentation aRepresentation, surface = mTextureHost->GetSurface()->GetIOSurfaceRef(); } return GetRepresentation(aRepresentation) - .ApplyChanges(aUpdate, mSize, mIsOpaque, mPosition, mTransform, mDisplayRect, mClipRect, - mBackingScale, mSurfaceIsFlipped, mSamplingFilter, mSpecializeVideo, surface, - mColor, mIsDRM, IsVideo()); + .ApplyChanges(aUpdate, mSize, mIsOpaque, mPosition, mTransform, + mDisplayRect, mClipRect, mBackingScale, mSurfaceIsFlipped, + mSamplingFilter, mSpecializeVideo, surface, mColor, mIsDRM, + IsVideo()); } CALayer* NativeLayerCA::UnderlyingCALayer(WhichRepresentation aRepresentation) { @@ -1423,8 +1528,10 @@ static NSString* NSStringForOSType(OSType type) { } bool NativeLayerCA::Representation::EnqueueSurface(IOSurfaceRef aSurfaceRef) { - MOZ_ASSERT([mContentCALayer isKindOfClass:[AVSampleBufferDisplayLayer class]]); - AVSampleBufferDisplayLayer* videoLayer = (AVSampleBufferDisplayLayer*)mContentCALayer; + MOZ_ASSERT( + [mContentCALayer isKindOfClass:[AVSampleBufferDisplayLayer class]]); + AVSampleBufferDisplayLayer* videoLayer = + (AVSampleBufferDisplayLayer*)mContentCALayer; if (@available(macOS 11.0, iOS 14.0, *)) { if (videoLayer.requiresFlushToResumeDecoding) { @@ -1442,12 +1549,14 @@ bool NativeLayerCA::Representation::EnqueueSurface(IOSurfaceRef aSurfaceRef) { return false; } - // Convert the IOSurfaceRef into a CMSampleBuffer, so we can enqueue it in mContentCALayer + // Convert the IOSurfaceRef into a CMSampleBuffer, so we can enqueue it in + // mContentCALayer CVPixelBufferRef pixelBuffer = nullptr; - CVReturn cvValue = - CVPixelBufferCreateWithIOSurface(kCFAllocatorDefault, aSurfaceRef, nullptr, &pixelBuffer); + CVReturn cvValue = CVPixelBufferCreateWithIOSurface( + kCFAllocatorDefault, aSurfaceRef, nullptr, &pixelBuffer); if (cvValue != kCVReturnSuccess) { - MOZ_ASSERT(pixelBuffer == nullptr, "Failed call shouldn't allocate memory."); + MOZ_ASSERT(pixelBuffer == nullptr, + "Failed call shouldn't allocate memory."); #ifdef NIGHTLY_BUILD if (StaticPrefs::gfx_core_animation_specialize_video_log()) { NSLog(@"VIDEO_LOG: EnqueueSurface failed on allocating pixel buffer."); @@ -1458,28 +1567,32 @@ bool NativeLayerCA::Representation::EnqueueSurface(IOSurfaceRef aSurfaceRef) { #ifdef NIGHTLY_BUILD if (StaticPrefs::gfx_core_animation_specialize_video_check_color_space()) { - // Ensure the resulting pixel buffer has a color space. If it doesn't, then modify - // the surface and create the buffer again. + // Ensure the resulting pixel buffer has a color space. If it doesn't, then + // modify the surface and create the buffer again. CFTypeRefPtr colorSpace = - CFTypeRefPtr::WrapUnderGetRule(CVImageBufferGetColorSpace(pixelBuffer)); + CFTypeRefPtr::WrapUnderGetRule( + CVImageBufferGetColorSpace(pixelBuffer)); if (!colorSpace) { // Use our main display color space. colorSpace = CFTypeRefPtr::WrapUnderCreateRule( CGDisplayCopyColorSpace(CGMainDisplayID())); - auto colorData = - CFTypeRefPtr::WrapUnderCreateRule(CGColorSpaceCopyICCData(colorSpace.get())); - IOSurfaceSetValue(aSurfaceRef, CFSTR("IOSurfaceColorSpace"), colorData.get()); + auto colorData = CFTypeRefPtr::WrapUnderCreateRule( + CGColorSpaceCopyICCData(colorSpace.get())); + IOSurfaceSetValue(aSurfaceRef, CFSTR("IOSurfaceColorSpace"), + colorData.get()); // Get rid of our old pixel buffer and create a new one. CFRelease(pixelBuffer); - cvValue = - CVPixelBufferCreateWithIOSurface(kCFAllocatorDefault, aSurfaceRef, nullptr, &pixelBuffer); + cvValue = CVPixelBufferCreateWithIOSurface( + kCFAllocatorDefault, aSurfaceRef, nullptr, &pixelBuffer); if (cvValue != kCVReturnSuccess) { - MOZ_ASSERT(pixelBuffer == nullptr, "Failed call shouldn't allocate memory."); + MOZ_ASSERT(pixelBuffer == nullptr, + "Failed call shouldn't allocate memory."); return false; } } - MOZ_ASSERT(CVImageBufferGetColorSpace(pixelBuffer), "Pixel buffer should have a color space."); + MOZ_ASSERT(CVImageBufferGetColorSpace(pixelBuffer), + "Pixel buffer should have a color space."); } #endif @@ -1487,22 +1600,26 @@ bool NativeLayerCA::Representation::EnqueueSurface(IOSurfaceRef aSurfaceRef) { CFTypeRefPtr::WrapUnderCreateRule(pixelBuffer); CMVideoFormatDescriptionRef formatDescription = nullptr; - OSStatus osValue = CMVideoFormatDescriptionCreateForImageBuffer(kCFAllocatorDefault, pixelBuffer, - &formatDescription); + OSStatus osValue = CMVideoFormatDescriptionCreateForImageBuffer( + kCFAllocatorDefault, pixelBuffer, &formatDescription); if (osValue != noErr) { - MOZ_ASSERT(formatDescription == nullptr, "Failed call shouldn't allocate memory."); + MOZ_ASSERT(formatDescription == nullptr, + "Failed call shouldn't allocate memory."); #ifdef NIGHTLY_BUILD if (StaticPrefs::gfx_core_animation_specialize_video_log()) { - NSLog(@"VIDEO_LOG: EnqueueSurface failed on allocating format description."); + NSLog(@"VIDEO_LOG: EnqueueSurface failed on allocating format " + @"description."); } #endif return false; } CFTypeRefPtr formatDescriptionDeallocator = - CFTypeRefPtr::WrapUnderCreateRule(formatDescription); + CFTypeRefPtr::WrapUnderCreateRule( + formatDescription); #ifdef NIGHTLY_BUILD - if (mLogNextVideoSurface && StaticPrefs::gfx_core_animation_specialize_video_log()) { + if (mLogNextVideoSurface && + StaticPrefs::gfx_core_animation_specialize_video_log()) { LogSurface(aSurfaceRef, pixelBuffer, formatDescription); mLogNextVideoSurface = false; } @@ -1515,18 +1632,21 @@ bool NativeLayerCA::Representation::EnqueueSurface(IOSurfaceRef aSurfaceRef) { spoofTiming = StaticPrefs::gfx_core_animation_specialize_video_spoof_timing(); #endif if (spoofTiming) { - // Since we don't have timing information for the sample, set the sample to play at the - // current timestamp. - CMTimebaseRef timebase = [(AVSampleBufferDisplayLayer*)mContentCALayer controlTimebase]; + // Since we don't have timing information for the sample, set the sample to + // play at the current timestamp. + CMTimebaseRef timebase = + [(AVSampleBufferDisplayLayer*)mContentCALayer controlTimebase]; CMTime nowTime = CMTimebaseGetTime(timebase); timingInfo = {.presentationTimeStamp = nowTime}; } CMSampleBufferRef sampleBuffer = nullptr; - osValue = CMSampleBufferCreateReadyWithImageBuffer(kCFAllocatorDefault, pixelBuffer, - formatDescription, &timingInfo, &sampleBuffer); + osValue = CMSampleBufferCreateReadyWithImageBuffer( + kCFAllocatorDefault, pixelBuffer, formatDescription, &timingInfo, + &sampleBuffer); if (osValue != noErr) { - MOZ_ASSERT(sampleBuffer == nullptr, "Failed call shouldn't allocate memory."); + MOZ_ASSERT(sampleBuffer == nullptr, + "Failed call shouldn't allocate memory."); #ifdef NIGHTLY_BUILD if (StaticPrefs::gfx_core_animation_specialize_video_log()) { NSLog(@"VIDEO_LOG: EnqueueSurface failed on allocating sample buffer."); @@ -1538,16 +1658,20 @@ bool NativeLayerCA::Representation::EnqueueSurface(IOSurfaceRef aSurfaceRef) { CFTypeRefPtr::WrapUnderCreateRule(sampleBuffer); if (!spoofTiming) { - // Since we don't have timing information for the sample, before we enqueue it, we - // attach an attribute that specifies that the sample should be played immediately. - CFArrayRef attachmentsArray = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, YES); + // Since we don't have timing information for the sample, before we enqueue + // it, we attach an attribute that specifies that the sample should be + // played immediately. + CFArrayRef attachmentsArray = + CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, YES); if (!attachmentsArray || CFArrayGetCount(attachmentsArray) == 0) { // No dictionary to alter. return false; } CFMutableDictionaryRef sample0Dictionary = - (__bridge CFMutableDictionaryRef)CFArrayGetValueAtIndex(attachmentsArray, 0); - CFDictionarySetValue(sample0Dictionary, kCMSampleAttachmentKey_DisplayImmediately, + (__bridge CFMutableDictionaryRef)CFArrayGetValueAtIndex( + attachmentsArray, 0); + CFDictionarySetValue(sample0Dictionary, + kCMSampleAttachmentKey_DisplayImmediately, kCFBooleanTrue); } @@ -1558,11 +1682,12 @@ bool NativeLayerCA::Representation::EnqueueSurface(IOSurfaceRef aSurfaceRef) { bool NativeLayerCA::Representation::ApplyChanges( NativeLayerCA::UpdateType aUpdate, const IntSize& aSize, bool aIsOpaque, - const IntPoint& aPosition, const Matrix4x4& aTransform, const IntRect& aDisplayRect, - const Maybe& aClipRect, float aBackingScale, bool aSurfaceIsFlipped, + const IntPoint& aPosition, const Matrix4x4& aTransform, + const IntRect& aDisplayRect, const Maybe& aClipRect, + float aBackingScale, bool aSurfaceIsFlipped, gfx::SamplingFilter aSamplingFilter, bool aSpecializeVideo, - CFTypeRefPtr aFrontSurface, CFTypeRefPtr aColor, bool aIsDRM, - bool aIsVideo) { + CFTypeRefPtr aFrontSurface, CFTypeRefPtr aColor, + bool aIsDRM, bool aIsVideo) { // If we have an OnlyVideo update, handle it and early exit. if (aUpdate == UpdateType::OnlyVideo) { // If we don't have any updates to do, exit early with success. This is @@ -1600,8 +1725,8 @@ bool NativeLayerCA::Representation::ApplyChanges( MOZ_ASSERT(aUpdate == UpdateType::All); if (mWrappingCALayer && mMutatedSpecializeVideo) { - // Since specialize video changes the way we construct our wrapping and content layers, - // we have to scrap them if this value has changed. + // Since specialize video changes the way we construct our wrapping and + // content layers, we have to scrap them if this value has changed. #ifdef NIGHTLY_BUILD if (aIsVideo && StaticPrefs::gfx_core_animation_specialize_video_log()) { NSLog(@"VIDEO_LOG: Scrapping existing video layer."); @@ -1627,29 +1752,36 @@ bool NativeLayerCA::Representation::ApplyChanges( mWrappingCALayer.edgeAntialiasingMask = 0; if (aColor) { - // Color layers set a color on the wrapping layer and don't get a content layer. + // Color layers set a color on the wrapping layer and don't get a content + // layer. mWrappingCALayer.backgroundColor = aColor.get(); } else { if (aSpecializeVideo) { #ifdef NIGHTLY_BUILD - if (aIsVideo && StaticPrefs::gfx_core_animation_specialize_video_log()) { - NSLog(@"VIDEO_LOG: Rebuilding video layer with AVSampleBufferDisplayLayer."); + if (aIsVideo && + StaticPrefs::gfx_core_animation_specialize_video_log()) { + NSLog(@"VIDEO_LOG: Rebuilding video layer with " + @"AVSampleBufferDisplayLayer."); mLogNextVideoSurface = true; } #endif mContentCALayer = [[AVSampleBufferDisplayLayer layer] retain]; CMTimebaseRef timebase; #ifdef CMTIMEBASE_USE_SOURCE_TERMINOLOGY - CMTimebaseCreateWithSourceClock(kCFAllocatorDefault, CMClockGetHostTimeClock(), &timebase); + CMTimebaseCreateWithSourceClock(kCFAllocatorDefault, + CMClockGetHostTimeClock(), &timebase); #else - CMTimebaseCreateWithMasterClock(kCFAllocatorDefault, CMClockGetHostTimeClock(), &timebase); + CMTimebaseCreateWithMasterClock(kCFAllocatorDefault, + CMClockGetHostTimeClock(), &timebase); #endif CMTimebaseSetRate(timebase, 1.0f); - [(AVSampleBufferDisplayLayer*)mContentCALayer setControlTimebase:timebase]; + [(AVSampleBufferDisplayLayer*)mContentCALayer + setControlTimebase:timebase]; CFRelease(timebase); } else { #ifdef NIGHTLY_BUILD - if (aIsVideo && StaticPrefs::gfx_core_animation_specialize_video_log()) { + if (aIsVideo && + StaticPrefs::gfx_core_animation_specialize_video_log()) { NSLog(@"VIDEO_LOG: Rebuilding video layer with CALayer."); mLogNextVideoSurface = true; } @@ -1664,8 +1796,8 @@ bool NativeLayerCA::Representation::ApplyChanges( mContentCALayer.edgeAntialiasingMask = 0; mContentCALayer.opaque = aIsOpaque; if ([mContentCALayer respondsToSelector:@selector(setContentsOpaque:)]) { - // The opaque property seems to not be enough when using IOSurface contents. - // Additionally, call the private method setContentsOpaque. + // The opaque property seems to not be enough when using IOSurface + // contents. Additionally, call the private method setContentsOpaque. [mContentCALayer setContentsOpaque:aIsOpaque]; } @@ -1698,29 +1830,33 @@ bool NativeLayerCA::Representation::ApplyChanges( mOpaquenessTintLayer = nullptr; } - // CALayers have a position and a size, specified through the position and the bounds properties. - // layer.bounds.origin must always be (0, 0). - // A layer's position affects the layer's entire layer subtree. In other words, each layer's - // position is relative to its superlayer's position. We implement the clip rect using - // masksToBounds on mWrappingCALayer. So mContentCALayer's position is relative to the clip rect - // position. - // Note: The Core Animation docs on "Positioning and Sizing Sublayers" say: - // Important: Always use integral numbers for the width and height of your layer. - // We hope that this refers to integral physical pixels, and not to integral logical coordinates. + // CALayers have a position and a size, specified through the position and the + // bounds properties. layer.bounds.origin must always be (0, 0). A layer's + // position affects the layer's entire layer subtree. In other words, each + // layer's position is relative to its superlayer's position. We implement the + // clip rect using masksToBounds on mWrappingCALayer. So mContentCALayer's + // position is relative to the clip rect position. Note: The Core Animation + // docs on "Positioning and Sizing Sublayers" say: + // Important: Always use integral numbers for the width and height of your + // layer. + // We hope that this refers to integral physical pixels, and not to integral + // logical coordinates. - if (mContentCALayer && (mMutatedBackingScale || mMutatedSize || layerNeedsInitialization)) { - mContentCALayer.bounds = - CGRectMake(0, 0, aSize.width / aBackingScale, aSize.height / aBackingScale); + if (mContentCALayer && + (mMutatedBackingScale || mMutatedSize || layerNeedsInitialization)) { + mContentCALayer.bounds = CGRectMake(0, 0, aSize.width / aBackingScale, + aSize.height / aBackingScale); if (mOpaquenessTintLayer) { mOpaquenessTintLayer.bounds = mContentCALayer.bounds; } mContentCALayer.contentsScale = aBackingScale; } - if (mMutatedBackingScale || mMutatedPosition || mMutatedDisplayRect || mMutatedClipRect || - mMutatedTransform || mMutatedSurfaceIsFlipped || mMutatedSize || layerNeedsInitialization) { - Maybe scaledClipRect = - CalculateClipGeometry(aSize, aPosition, aTransform, aDisplayRect, aClipRect, aBackingScale); + if (mMutatedBackingScale || mMutatedPosition || mMutatedDisplayRect || + mMutatedClipRect || mMutatedTransform || mMutatedSurfaceIsFlipped || + mMutatedSize || layerNeedsInitialization) { + Maybe scaledClipRect = CalculateClipGeometry( + aSize, aPosition, aTransform, aDisplayRect, aClipRect, aBackingScale); CGRect useClipRect; if (scaledClipRect.isSome()) { @@ -1730,7 +1866,8 @@ bool NativeLayerCA::Representation::ApplyChanges( } mWrappingCALayer.position = useClipRect.origin; - mWrappingCALayer.bounds = CGRectMake(0, 0, useClipRect.size.width, useClipRect.size.height); + mWrappingCALayer.bounds = + CGRectMake(0, 0, useClipRect.size.width, useClipRect.size.height); mWrappingCALayer.masksToBounds = scaledClipRect.isSome(); if (mContentCALayer) { @@ -1799,7 +1936,8 @@ bool NativeLayerCA::Representation::ApplyChanges( } } else { #ifdef NIGHTLY_BUILD - if (mLogNextVideoSurface && StaticPrefs::gfx_core_animation_specialize_video_log()) { + if (mLogNextVideoSurface && + StaticPrefs::gfx_core_animation_specialize_video_log()) { LogSurface(surface, nullptr, nullptr); mLogNextVideoSurface = false; } @@ -1823,22 +1961,25 @@ bool NativeLayerCA::Representation::ApplyChanges( return true; } -NativeLayerCA::UpdateType NativeLayerCA::Representation::HasUpdate(bool aIsVideo) { +NativeLayerCA::UpdateType NativeLayerCA::Representation::HasUpdate( + bool aIsVideo) { if (!mWrappingCALayer) { return UpdateType::All; } - // This check intentionally skips mMutatedFrontSurface. We'll check it later to see - // if we can attempt an OnlyVideo update. - if (mMutatedPosition || mMutatedTransform || mMutatedDisplayRect || mMutatedClipRect || - mMutatedBackingScale || mMutatedSize || mMutatedSurfaceIsFlipped || mMutatedSamplingFilter || + // This check intentionally skips mMutatedFrontSurface. We'll check it later + // to see if we can attempt an OnlyVideo update. + if (mMutatedPosition || mMutatedTransform || mMutatedDisplayRect || + mMutatedClipRect || mMutatedBackingScale || mMutatedSize || + mMutatedSurfaceIsFlipped || mMutatedSamplingFilter || mMutatedSpecializeVideo || mMutatedIsDRM) { return UpdateType::All; } - // Check if we should try an OnlyVideo update. We know from the above check that our - // specialize video is stable (we don't know what value we'll receive, though), so - // we just have to check that we have a surface to display. + // Check if we should try an OnlyVideo update. We know from the above check + // that our specialize video is stable (we don't know what value we'll + // receive, though), so we just have to check that we have a surface to + // display. if (mMutatedFrontSurface) { return (aIsVideo ? UpdateType::OnlyVideo : UpdateType::All); } @@ -1846,15 +1987,16 @@ NativeLayerCA::UpdateType NativeLayerCA::Representation::HasUpdate(bool aIsVideo return UpdateType::None; } -bool NativeLayerCA::WillUpdateAffectLayers(WhichRepresentation aRepresentation) { +bool NativeLayerCA::WillUpdateAffectLayers( + WhichRepresentation aRepresentation) { MutexAutoLock lock(mMutex); auto& r = GetRepresentation(aRepresentation); return r.mMutatedSpecializeVideo || !r.UnderlyingCALayer(); } // Called when mMutex is already being held by the current thread. -Maybe NativeLayerCA::GetUnusedSurfaceAndCleanUp( - const MutexAutoLock& aProofOfLock) { +Maybe +NativeLayerCA::GetUnusedSurfaceAndCleanUp(const MutexAutoLock& aProofOfLock) { std::vector usedSurfaces; Maybe unusedSurface; @@ -1865,17 +2007,21 @@ Maybe NativeLayerCA::GetUnusedSurfaceAn if (surf.mCheckCount < 10) { usedSurfaces.push_back(std::move(surf)); } else { - // The window server has been holding on to this surface for an unreasonably long time. This - // is known to happen sometimes, for example in occluded windows or after a GPU switch. In - // that case, release our references to the surface so that it doesn't look like we're - // trying to keep it alive. - mSurfacePoolHandle->ReturnSurfaceToPool(std::move(surf.mEntry.mSurface)); + // The window server has been holding on to this surface for an + // unreasonably long time. This is known to happen sometimes, for + // example in occluded windows or after a GPU switch. In that case, + // release our references to the surface so that it doesn't look like + // we're trying to keep it alive. + mSurfacePoolHandle->ReturnSurfaceToPool( + std::move(surf.mEntry.mSurface)); } } else { if (unusedSurface) { - // Multiple surfaces are unused. Keep the most recent one and release any earlier ones. The - // most recent one requires the least amount of copying during partial repaints. - mSurfacePoolHandle->ReturnSurfaceToPool(std::move(unusedSurface->mSurface)); + // Multiple surfaces are unused. Keep the most recent one and release + // any earlier ones. The most recent one requires the least amount of + // copying during partial repaints. + mSurfacePoolHandle->ReturnSurfaceToPool( + std::move(unusedSurface->mSurface)); } unusedSurface = Some(std::move(surf.mEntry)); } @@ -1887,24 +2033,28 @@ Maybe NativeLayerCA::GetUnusedSurfaceAn return unusedSurface; } -bool DownscaleTargetNLRS::DownscaleFrom(profiler_screenshots::RenderSource* aSource, - const IntRect& aSourceRect, const IntRect& aDestRect) { - mGL->BlitHelper()->BlitFramebufferToFramebuffer(static_cast(aSource)->FB().mFB, - mRenderSource->FB().mFB, aSourceRect, aDestRect, - LOCAL_GL_LINEAR); +bool DownscaleTargetNLRS::DownscaleFrom( + profiler_screenshots::RenderSource* aSource, const IntRect& aSourceRect, + const IntRect& aDestRect) { + mGL->BlitHelper()->BlitFramebufferToFramebuffer( + static_cast(aSource)->FB().mFB, + mRenderSource->FB().mFB, aSourceRect, aDestRect, LOCAL_GL_LINEAR); return true; } -void AsyncReadbackBufferNLRS::CopyFrom(profiler_screenshots::RenderSource* aSource) { +void AsyncReadbackBufferNLRS::CopyFrom( + profiler_screenshots::RenderSource* aSource) { IntSize size = aSource->Size(); MOZ_RELEASE_ASSERT(Size() == size); gl::ScopedPackState scopedPackState(mGL); mGL->fBindBuffer(LOCAL_GL_PIXEL_PACK_BUFFER, mBufferHandle); mGL->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, 1); - const gl::ScopedBindFramebuffer bindFB(mGL, static_cast(aSource)->FB().mFB); - mGL->fReadPixels(0, 0, size.width, size.height, LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_BYTE, 0); + const gl::ScopedBindFramebuffer bindFB( + mGL, static_cast(aSource)->FB().mFB); + mGL->fReadPixels(0, 0, size.width, size.height, LOCAL_GL_RGBA, + LOCAL_GL_UNSIGNED_BYTE, 0); } bool AsyncReadbackBufferNLRS::MapAndCopyInto(DataSourceSurface* aSurface, @@ -1921,12 +2071,12 @@ bool AsyncReadbackBufferNLRS::MapAndCopyInto(DataSourceSurface* aSurface, const uint8_t* srcData = nullptr; if (mGL->IsSupported(gl::GLFeature::map_buffer_range)) { - srcData = static_cast(mGL->fMapBufferRange(LOCAL_GL_PIXEL_PACK_BUFFER, 0, - aReadSize.height * aReadSize.width * 4, - LOCAL_GL_MAP_READ_BIT)); + srcData = static_cast(mGL->fMapBufferRange( + LOCAL_GL_PIXEL_PACK_BUFFER, 0, aReadSize.height * aReadSize.width * 4, + LOCAL_GL_MAP_READ_BIT)); } else { - srcData = - static_cast(mGL->fMapBuffer(LOCAL_GL_PIXEL_PACK_BUFFER, LOCAL_GL_READ_ONLY)); + srcData = static_cast( + mGL->fMapBuffer(LOCAL_GL_PIXEL_PACK_BUFFER, LOCAL_GL_READ_ONLY)); } if (!srcData) { @@ -1943,8 +2093,8 @@ bool AsyncReadbackBufferNLRS::MapAndCopyInto(DataSourceSurface* aSurface, int32_t srcRow = aReadSize.height - 1 - destRow; const uint8_t* src = &srcData[srcRow * srcStride]; uint8_t* dest = &destData[destRow * destStride]; - SwizzleData(src, srcStride, SurfaceFormat::R8G8B8A8, dest, destStride, destFormat, - IntSize(aReadSize.width, 1)); + SwizzleData(src, srcStride, SurfaceFormat::R8G8B8A8, dest, destStride, + destFormat, IntSize(aReadSize.width, 1)); } mGL->fUnmapBuffer(LOCAL_GL_PIXEL_PACK_BUFFER); diff --git a/gfx/layers/SurfacePoolCA.mm b/gfx/layers/SurfacePoolCA.mm index f5fc0201bfbf..47b2663ed7c7 100644 --- a/gfx/layers/SurfacePoolCA.mm +++ b/gfx/layers/SurfacePoolCA.mm @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nullptr; c-basic-offset: 2 -*- +/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -36,11 +36,13 @@ using gl::GLContextCGL; // SurfacePoolCA::LockedPool -SurfacePoolCA::LockedPool::LockedPool(size_t aPoolSizeLimit) : mPoolSizeLimit(aPoolSizeLimit) {} +SurfacePoolCA::LockedPool::LockedPool(size_t aPoolSizeLimit) + : mPoolSizeLimit(aPoolSizeLimit) {} SurfacePoolCA::LockedPool::~LockedPool() { - MOZ_RELEASE_ASSERT(mWrappers.empty(), - "Any outstanding wrappers should have kept the surface pool alive"); + MOZ_RELEASE_ASSERT( + mWrappers.empty(), + "Any outstanding wrappers should have kept the surface pool alive"); MOZ_RELEASE_ASSERT(mInUseEntries.empty(), "Leak! No more surfaces should be in use at this point."); // Remove all entries in mPendingEntries and mAvailableEntries. @@ -50,8 +52,8 @@ SurfacePoolCA::LockedPool::~LockedPool() { }); } -RefPtr SurfacePoolCA::LockedPool::GetWrapperForGL(SurfacePoolCA* aPool, - GLContext* aGL) { +RefPtr SurfacePoolCA::LockedPool::GetWrapperForGL( + SurfacePoolCA* aPool, GLContext* aGL) { auto& wrapper = mWrappers[aGL]; if (!wrapper) { wrapper = new SurfacePoolCAWrapperForGL(aPool, aGL); @@ -71,7 +73,8 @@ void SurfacePoolCA::LockedPool::DestroyGLResourcesForContext(GLContext* aGL) { template void SurfacePoolCA::LockedPool::MutateEntryStorage(const char* aMutationType, - const gfx::IntSize& aSize, F aFn) { + const gfx::IntSize& aSize, + F aFn) { [[maybe_unused]] size_t inUseCountBefore = mInUseEntries.size(); [[maybe_unused]] size_t pendingCountBefore = mPendingEntries.Length(); [[maybe_unused]] size_t availableCountBefore = mAvailableEntries.Length(); @@ -84,9 +87,11 @@ void SurfacePoolCA::LockedPool::MutateEntryStorage(const char* aMutationType, "SurfacePool", GRAPHICS, MarkerTiming::IntervalUntilNowFrom(before), nsPrintfCString("%d -> %d in use | %d -> %d waiting for | %d -> %d " "available | %s %dx%d | %dMB total memory", - int(inUseCountBefore), int(mInUseEntries.size()), int(pendingCountBefore), - int(mPendingEntries.Length()), int(availableCountBefore), - int(mAvailableEntries.Length()), aMutationType, aSize.width, aSize.height, + int(inUseCountBefore), int(mInUseEntries.size()), + int(pendingCountBefore), int(mPendingEntries.Length()), + int(availableCountBefore), + int(mAvailableEntries.Length()), aMutationType, + aSize.width, aSize.height, int(EstimateTotalMemory() / 1000 / 1000))); } } @@ -126,8 +131,8 @@ uint64_t SurfacePoolCA::LockedPool::EstimateTotalMemory() { return memBytes; } -bool SurfacePoolCA::LockedPool::CanRecycleSurfaceForRequest(const SurfacePoolEntry& aEntry, - const IntSize& aSize, GLContext* aGL) { +bool SurfacePoolCA::LockedPool::CanRecycleSurfaceForRequest( + const SurfacePoolEntry& aEntry, const IntSize& aSize, GLContext* aGL) { if (aEntry.mSize != aSize) { return false; } @@ -137,14 +142,16 @@ bool SurfacePoolCA::LockedPool::CanRecycleSurfaceForRequest(const SurfacePoolEnt return true; } -CFTypeRefPtr SurfacePoolCA::LockedPool::ObtainSurfaceFromPool(const IntSize& aSize, - GLContext* aGL) { - // Do a linear scan through mAvailableEntries to find an eligible surface, going from oldest to - // newest. The size of this array is limited, so the linear scan is fast. - auto iterToRecycle = std::find_if(mAvailableEntries.begin(), mAvailableEntries.end(), - [&](const SurfacePoolEntry& aEntry) { - return CanRecycleSurfaceForRequest(aEntry, aSize, aGL); - }); +CFTypeRefPtr SurfacePoolCA::LockedPool::ObtainSurfaceFromPool( + const IntSize& aSize, GLContext* aGL) { + // Do a linear scan through mAvailableEntries to find an eligible surface, + // going from oldest to newest. The size of this array is limited, so the + // linear scan is fast. + auto iterToRecycle = + std::find_if(mAvailableEntries.begin(), mAvailableEntries.end(), + [&](const SurfacePoolEntry& aEntry) { + return CanRecycleSurfaceForRequest(aEntry, aSize, aGL); + }); if (iterToRecycle != mAvailableEntries.end()) { CFTypeRefPtr surface = iterToRecycle->mIOSurface; MOZ_RELEASE_ASSERT(surface.get(), "Available surfaces should be non-null."); @@ -156,18 +163,22 @@ CFTypeRefPtr SurfacePoolCA::LockedPool::ObtainSurfaceFromPool(cons return surface; } - AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING("IOSurface creation", GRAPHICS_TileAllocation, - nsPrintfCString("%dx%d", aSize.width, aSize.height)); + AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING( + "IOSurface creation", GRAPHICS_TileAllocation, + nsPrintfCString("%dx%d", aSize.width, aSize.height)); CFTypeRefPtr surface = - CFTypeRefPtr::WrapUnderCreateRule(IOSurfaceCreate((__bridge CFDictionaryRef) @{ - (__bridge NSString*)kIOSurfaceWidth : @(aSize.width), - (__bridge NSString*)kIOSurfaceHeight : @(aSize.height), - (__bridge NSString*)kIOSurfacePixelFormat : @(kCVPixelFormatType_32BGRA), - (__bridge NSString*)kIOSurfaceBytesPerElement : @(4), - })); + CFTypeRefPtr::WrapUnderCreateRule( + IOSurfaceCreate((__bridge CFDictionaryRef) @{ + (__bridge NSString*)kIOSurfaceWidth : @(aSize.width), + (__bridge NSString*)kIOSurfaceHeight : @(aSize.height), + (__bridge NSString*) + kIOSurfacePixelFormat : @(kCVPixelFormatType_32BGRA), + (__bridge NSString*)kIOSurfaceBytesPerElement : @(4), + })); if (surface) { if (StaticPrefs::gfx_color_management_native_srgb()) { - IOSurfaceSetValue(surface.get(), CFSTR("IOSurfaceColorSpace"), kCGColorSpaceSRGB); + IOSurfaceSetValue(surface.get(), CFSTR("IOSurfaceColorSpace"), + kCGColorSpaceSRGB); } // Create a new entry in mInUseEntries. MutateEntryStorage("Create", aSize, [&]() { @@ -177,16 +188,18 @@ CFTypeRefPtr SurfacePoolCA::LockedPool::ObtainSurfaceFromPool(cons return surface; } -void SurfacePoolCA::LockedPool::ReturnSurfaceToPool(CFTypeRefPtr aSurface) { +void SurfacePoolCA::LockedPool::ReturnSurfaceToPool( + CFTypeRefPtr aSurface) { auto inUseEntryIter = mInUseEntries.find(aSurface); MOZ_RELEASE_ASSERT(inUseEntryIter != mInUseEntries.end()); if (IOSurfaceIsInUse(aSurface.get())) { // Move the entry from mInUseEntries to mPendingEntries. - MutateEntryStorage("Start waiting for", IntSize(inUseEntryIter->second.mSize), [&]() { - mPendingEntries.AppendElement( - PendingSurfaceEntry{std::move(inUseEntryIter->second), mCollectionGeneration, 0}); - mInUseEntries.erase(inUseEntryIter); - }); + MutateEntryStorage( + "Start waiting for", IntSize(inUseEntryIter->second.mSize), [&]() { + mPendingEntries.AppendElement(PendingSurfaceEntry{ + std::move(inUseEntryIter->second), mCollectionGeneration, 0}); + mInUseEntries.erase(inUseEntryIter); + }); } else { // Move the entry from mInUseEntries to mAvailableEntries. MOZ_RELEASE_ASSERT(inUseEntryIter->second.mIOSurface.get(), @@ -199,14 +212,16 @@ void SurfacePoolCA::LockedPool::ReturnSurfaceToPool(CFTypeRefPtr a } void SurfacePoolCA::LockedPool::EnforcePoolSizeLimit() { - // Enforce the pool size limit, removing least-recently-used entries as necessary. + // Enforce the pool size limit, removing least-recently-used entries as + // necessary. while (mAvailableEntries.Length() > mPoolSizeLimit) { MutateEntryStorage("Evict", IntSize(mAvailableEntries[0].mSize), [&]() { mAvailableEntries.RemoveElementAt(0); }); } } -uint64_t SurfacePoolCA::LockedPool::CollectPendingSurfaces(uint64_t aCheckGenerationsUpTo) { +uint64_t SurfacePoolCA::LockedPool::CollectPendingSurfaces( + uint64_t aCheckGenerationsUpTo) { mCollectionGeneration++; // Loop from back to front, potentially deleting items as we iterate. @@ -218,18 +233,21 @@ uint64_t SurfacePoolCA::LockedPool::CollectPendingSurfaces(uint64_t aCheckGenera if (pendingSurf.mPreviousCheckGeneration > aCheckGenerationsUpTo) { continue; } - // Check if the window server is still using the surface. As long as it is doing that, we cannot - // move the surface to mAvailableSurfaces because anything we draw to it could reach the screen - // in a place where we don't expect it. + // Check if the window server is still using the surface. As long as it is + // doing that, we cannot move the surface to mAvailableSurfaces because + // anything we draw to it could reach the screen in a place where we don't + // expect it. if (IOSurfaceIsInUse(pendingSurf.mEntry.mIOSurface.get())) { - // The surface is still in use. Update mPreviousCheckGeneration and mCheckCount. + // The surface is still in use. Update mPreviousCheckGeneration and + // mCheckCount. pendingSurf.mPreviousCheckGeneration = mCollectionGeneration; pendingSurf.mCheckCount++; if (pendingSurf.mCheckCount >= 30) { - // The window server has been holding on to this surface for an unreasonably long time. This - // is known to happen sometimes, for example in occluded windows or after a GPU switch. In - // that case, release our references to the surface so that it's Not Our Problem anymore. - // Remove the entry from mPendingEntries. + // The window server has been holding on to this surface for an + // unreasonably long time. This is known to happen sometimes, for + // example in occluded windows or after a GPU switch. In that case, + // release our references to the surface so that it's Not Our Problem + // anymore. Remove the entry from mPendingEntries. MutateEntryStorage("Eject", IntSize(pendingSurf.mEntry.mSize), [&]() { mPendingEntries.RemoveElementAt(i); }); } @@ -238,30 +256,33 @@ uint64_t SurfacePoolCA::LockedPool::CollectPendingSurfaces(uint64_t aCheckGenera // Move the entry from mPendingEntries to mAvailableEntries. MOZ_RELEASE_ASSERT(pendingSurf.mEntry.mIOSurface.get(), "Pending surfaces should be non-null."); - MutateEntryStorage("Stop waiting for", IntSize(pendingSurf.mEntry.mSize), [&]() { - mAvailableEntries.AppendElement(std::move(pendingSurf.mEntry)); - mPendingEntries.RemoveElementAt(i); - }); + MutateEntryStorage( + "Stop waiting for", IntSize(pendingSurf.mEntry.mSize), [&]() { + mAvailableEntries.AppendElement(std::move(pendingSurf.mEntry)); + mPendingEntries.RemoveElementAt(i); + }); } } return mCollectionGeneration; } -void SurfacePoolCA::LockedPool::OnWrapperDestroyed(gl::GLContext* aGL, - SurfacePoolCAWrapperForGL* aWrapper) { +void SurfacePoolCA::LockedPool::OnWrapperDestroyed( + gl::GLContext* aGL, SurfacePoolCAWrapperForGL* aWrapper) { if (aGL) { DestroyGLResourcesForContext(aGL); } auto iter = mWrappers.find(aGL); MOZ_RELEASE_ASSERT(iter != mWrappers.end()); - MOZ_RELEASE_ASSERT(iter->second == aWrapper, "Only one SurfacePoolCAWrapperForGL object should " - "exist for each GLContext* at any time"); + MOZ_RELEASE_ASSERT(iter->second == aWrapper, + "Only one SurfacePoolCAWrapperForGL object should " + "exist for each GLContext* at any time"); mWrappers.erase(iter); } Maybe SurfacePoolCA::LockedPool::GetFramebufferForSurface( - CFTypeRefPtr aSurface, GLContext* aGL, bool aNeedsDepthBuffer) { + CFTypeRefPtr aSurface, GLContext* aGL, + bool aNeedsDepthBuffer) { MOZ_RELEASE_ASSERT(aGL); auto inUseEntryIter = mInUseEntries.find(aSurface); @@ -271,7 +292,8 @@ Maybe SurfacePoolCA::LockedPool::GetFramebufferForSurface( if (entry.mGLResources) { // We have an existing framebuffer. MOZ_RELEASE_ASSERT(entry.mGLResources->mGLContext == aGL, - "Recycled surface that still had GL resources from a different GL context. " + "Recycled surface that still had GL resources from a " + "different GL context. " "This shouldn't happen."); if (!aNeedsDepthBuffer || entry.mGLResources->mFramebuffer->HasDepth()) { return Some(entry.mGLResources->mFramebuffer->mFB); @@ -294,13 +316,16 @@ Maybe SurfacePoolCA::LockedPool::GetFramebufferForSurface( GLuint tex = aGL->CreateTexture(); { - const gl::ScopedBindTexture bindTex(aGL, tex, LOCAL_GL_TEXTURE_RECTANGLE_ARB); - CGLTexImageIOSurface2D(cgl->GetCGLContext(), LOCAL_GL_TEXTURE_RECTANGLE_ARB, LOCAL_GL_RGBA, - entry.mSize.width, entry.mSize.height, LOCAL_GL_BGRA, - LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV, entry.mIOSurface.get(), 0); + const gl::ScopedBindTexture bindTex(aGL, tex, + LOCAL_GL_TEXTURE_RECTANGLE_ARB); + CGLTexImageIOSurface2D(cgl->GetCGLContext(), LOCAL_GL_TEXTURE_RECTANGLE_ARB, + LOCAL_GL_RGBA, entry.mSize.width, entry.mSize.height, + LOCAL_GL_BGRA, LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV, + entry.mIOSurface.get(), 0); } - auto fb = CreateFramebufferForTexture(aGL, entry.mSize, tex, aNeedsDepthBuffer); + auto fb = + CreateFramebufferForTexture(aGL, entry.mSize, tex, aNeedsDepthBuffer); if (!fb) { // Framebuffer completeness check may have failed. return {}; @@ -311,10 +336,12 @@ Maybe SurfacePoolCA::LockedPool::GetFramebufferForSurface( return Some(fbo); } -RefPtr SurfacePoolCA::LockedPool::GetDepthBufferForSharing( - GLContext* aGL, const IntSize& aSize) { +RefPtr +SurfacePoolCA::LockedPool::GetDepthBufferForSharing(GLContext* aGL, + const IntSize& aSize) { // Clean out entries for which the weak pointer has become null. - mDepthBuffers.RemoveElementsBy([&](const DepthBufferEntry& entry) { return !entry.mBuffer; }); + mDepthBuffers.RemoveElementsBy( + [&](const DepthBufferEntry& entry) { return !entry.mBuffer; }); for (const auto& entry : mDepthBuffers) { if (entry.mGLContext == aGL && entry.mSize == aSize) { @@ -324,22 +351,29 @@ RefPtr SurfacePoolCA::LockedPool::GetDepthBufferForSh return nullptr; } -UniquePtr SurfacePoolCA::LockedPool::CreateFramebufferForTexture( - GLContext* aGL, const IntSize& aSize, GLuint aTexture, bool aNeedsDepthBuffer) { +UniquePtr +SurfacePoolCA::LockedPool::CreateFramebufferForTexture(GLContext* aGL, + const IntSize& aSize, + GLuint aTexture, + bool aNeedsDepthBuffer) { if (aNeedsDepthBuffer) { - // Try to find an existing depth buffer of aSize in aGL and create a framebuffer that shares it. + // Try to find an existing depth buffer of aSize in aGL and create a + // framebuffer that shares it. if (auto buffer = GetDepthBufferForSharing(aGL, aSize)) { return gl::MozFramebuffer::CreateForBackingWithSharedDepthAndStencil( aSize, 0, LOCAL_GL_TEXTURE_RECTANGLE_ARB, aTexture, buffer); } } - // No depth buffer needed or we didn't find one. Create a framebuffer with a new depth buffer and - // store a weak pointer to the new depth buffer in mDepthBuffers. + // No depth buffer needed or we didn't find one. Create a framebuffer with a + // new depth buffer and store a weak pointer to the new depth buffer in + // mDepthBuffers. UniquePtr fb = gl::MozFramebuffer::CreateForBacking( - aGL, aSize, 0, aNeedsDepthBuffer, LOCAL_GL_TEXTURE_RECTANGLE_ARB, aTexture); + aGL, aSize, 0, aNeedsDepthBuffer, LOCAL_GL_TEXTURE_RECTANGLE_ARB, + aTexture); if (fb && fb->GetDepthAndStencilBuffer()) { - mDepthBuffers.AppendElement(DepthBufferEntry{aGL, aSize, fb->GetDepthAndStencilBuffer().get()}); + mDepthBuffers.AppendElement( + DepthBufferEntry{aGL, aSize, fb->GetDepthAndStencilBuffer().get()}); } return fb; @@ -347,8 +381,9 @@ UniquePtr SurfacePoolCA::LockedPool::CreateFramebufferForTex // SurfacePoolHandleCA -SurfacePoolHandleCA::SurfacePoolHandleCA(RefPtr&& aPoolWrapper, - uint64_t aCurrentCollectionGeneration) +SurfacePoolHandleCA::SurfacePoolHandleCA( + RefPtr&& aPoolWrapper, + uint64_t aCurrentCollectionGeneration) : mPoolWrapper(aPoolWrapper), mPreviousFrameCollectionGeneration( "SurfacePoolHandleCA::mPreviousFrameCollectionGeneration") { @@ -363,20 +398,24 @@ void SurfacePoolHandleCA::OnBeginFrame() { *generation = mPoolWrapper->mPool->CollectPendingSurfaces(*generation); } -void SurfacePoolHandleCA::OnEndFrame() { mPoolWrapper->mPool->EnforcePoolSizeLimit(); } +void SurfacePoolHandleCA::OnEndFrame() { + mPoolWrapper->mPool->EnforcePoolSizeLimit(); +} -CFTypeRefPtr SurfacePoolHandleCA::ObtainSurfaceFromPool(const IntSize& aSize) { +CFTypeRefPtr SurfacePoolHandleCA::ObtainSurfaceFromPool( + const IntSize& aSize) { return mPoolWrapper->mPool->ObtainSurfaceFromPool(aSize, mPoolWrapper->mGL); } -void SurfacePoolHandleCA::ReturnSurfaceToPool(CFTypeRefPtr aSurface) { +void SurfacePoolHandleCA::ReturnSurfaceToPool( + CFTypeRefPtr aSurface) { mPoolWrapper->mPool->ReturnSurfaceToPool(aSurface); } -Maybe SurfacePoolHandleCA::GetFramebufferForSurface(CFTypeRefPtr aSurface, - bool aNeedsDepthBuffer) { - return mPoolWrapper->mPool->GetFramebufferForSurface(aSurface, mPoolWrapper->mGL, - aNeedsDepthBuffer); +Maybe SurfacePoolHandleCA::GetFramebufferForSurface( + CFTypeRefPtr aSurface, bool aNeedsDepthBuffer) { + return mPoolWrapper->mPool->GetFramebufferForSurface( + aSurface, mPoolWrapper->mGL, aNeedsDepthBuffer); } // SurfacePoolCA @@ -405,8 +444,8 @@ void SurfacePoolCA::DestroyGLResourcesForContext(GLContext* aGL) { pool->DestroyGLResourcesForContext(aGL); } -CFTypeRefPtr SurfacePoolCA::ObtainSurfaceFromPool(const IntSize& aSize, - GLContext* aGL) { +CFTypeRefPtr SurfacePoolCA::ObtainSurfaceFromPool( + const IntSize& aSize, GLContext* aGL) { auto pool = mPool.Lock(); return pool->ObtainSurfaceFromPool(aSize, aGL); } @@ -425,13 +464,15 @@ void SurfacePoolCA::EnforcePoolSizeLimit() { pool->EnforcePoolSizeLimit(); } -Maybe SurfacePoolCA::GetFramebufferForSurface(CFTypeRefPtr aSurface, - GLContext* aGL, bool aNeedsDepthBuffer) { +Maybe SurfacePoolCA::GetFramebufferForSurface( + CFTypeRefPtr aSurface, GLContext* aGL, + bool aNeedsDepthBuffer) { auto pool = mPool.Lock(); return pool->GetFramebufferForSurface(aSurface, aGL, aNeedsDepthBuffer); } -void SurfacePoolCA::OnWrapperDestroyed(gl::GLContext* aGL, SurfacePoolCAWrapperForGL* aWrapper) { +void SurfacePoolCA::OnWrapperDestroyed(gl::GLContext* aGL, + SurfacePoolCAWrapperForGL* aWrapper) { auto pool = mPool.Lock(); return pool->OnWrapperDestroyed(aGL, aWrapper); } diff --git a/gfx/thebes/PrintTargetCG.mm b/gfx/thebes/PrintTargetCG.mm index ad60fbd897e0..cbd376906765 100644 --- a/gfx/thebes/PrintTargetCG.mm +++ b/gfx/thebes/PrintTargetCG.mm @@ -15,10 +15,14 @@ namespace mozilla::gfx { -static size_t PutBytesNull(void* info, const void* buffer, size_t count) { return count; } +static size_t PutBytesNull(void* info, const void* buffer, size_t count) { + return count; +} -PrintTargetCG::PrintTargetCG(CGContextRef aPrintToStreamContext, PMPrintSession aPrintSession, - PMPageFormat aPageFormat, PMPrintSettings aPrintSettings, +PrintTargetCG::PrintTargetCG(CGContextRef aPrintToStreamContext, + PMPrintSession aPrintSession, + PMPageFormat aPageFormat, + PMPrintSettings aPrintSettings, const IntSize& aSize) : PrintTarget(/* aCairoSurface */ nullptr, aSize), mPrintToStreamContext(aPrintToStreamContext), @@ -53,14 +57,16 @@ PrintTargetCG::~PrintTargetCG() { NS_OBJC_END_TRY_IGNORE_BLOCK; } -static size_t WriteStreamBytes(void* aInfo, const void* aBuffer, size_t aCount) { +static size_t WriteStreamBytes(void* aInfo, const void* aBuffer, + size_t aCount) { auto* stream = static_cast(aInfo); auto* data = static_cast(aBuffer); size_t remaining = aCount; do { uint32_t wrote = 0; // Handle potential narrowing from size_t to uint32_t. - uint32_t toWrite = uint32_t(std::min(remaining, size_t(std::numeric_limits::max()))); + uint32_t toWrite = uint32_t( + std::min(remaining, size_t(std::numeric_limits::max()))); if (NS_WARN_IF(NS_FAILED(stream->Write(data, toWrite, &wrote)))) { break; } @@ -87,21 +93,25 @@ static CGContextRef CreatePrintToStreamContext(nsIOutputStream* aOutputStream, CGDataConsumerRef consumer = CGDataConsumerCreate(aOutputStream, &callbacks); // This metadata is added by the CorePrinting APIs in the non-stream case. - NSString* bundleName = - [NSBundle.mainBundle.localizedInfoDictionary objectForKey:(NSString*)kCFBundleNameKey]; + NSString* bundleName = [NSBundle.mainBundle.localizedInfoDictionary + objectForKey:(NSString*)kCFBundleNameKey]; CFMutableDictionaryRef auxiliaryInfo = CFDictionaryCreateMutable( - kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFDictionaryAddValue(auxiliaryInfo, kCGPDFContextCreator, (__bridge CFStringRef)bundleName); + kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + CFDictionaryAddValue(auxiliaryInfo, kCGPDFContextCreator, + (__bridge CFStringRef)bundleName); - CGContextRef pdfContext = CGPDFContextCreate(consumer, &pageBox, auxiliaryInfo); + CGContextRef pdfContext = + CGPDFContextCreate(consumer, &pageBox, auxiliaryInfo); CGDataConsumerRelease(consumer); CFRelease(auxiliaryInfo); return pdfContext; } /* static */ already_AddRefed PrintTargetCG::CreateOrNull( - nsIOutputStream* aOutputStream, PMPrintSession aPrintSession, PMPageFormat aPageFormat, - PMPrintSettings aPrintSettings, const IntSize& aSize) { + nsIOutputStream* aOutputStream, PMPrintSession aPrintSession, + PMPageFormat aPageFormat, PMPrintSettings aPrintSettings, + const IntSize& aSize) { if (!Factory::CheckSurfaceSize(aSize)) { return nullptr; } @@ -114,8 +124,8 @@ static CGContextRef CreatePrintToStreamContext(nsIOutputStream* aOutputStream, } } - RefPtr target = - new PrintTargetCG(printToStreamContext, aPrintSession, aPageFormat, aPrintSettings, aSize); + RefPtr target = new PrintTargetCG( + printToStreamContext, aPrintSession, aPageFormat, aPrintSettings, aSize); return target.forget(); } @@ -129,8 +139,8 @@ already_AddRefed PrintTargetCG::GetReferenceDrawTarget() { CGContextRef pdfContext = CGPDFContextCreate(consumer, nullptr, nullptr); CGDataConsumerRelease(consumer); - cairo_surface_t* similar = - cairo_quartz_surface_create_for_cg_context(pdfContext, size.width, size.height); + cairo_surface_t* similar = cairo_quartz_surface_create_for_cg_context( + pdfContext, size.width, size.height); CGContextRelease(pdfContext); @@ -138,7 +148,8 @@ already_AddRefed PrintTargetCG::GetReferenceDrawTarget() { return nullptr; } - RefPtr dt = Factory::CreateDrawTargetForCairoSurface(similar, size); + RefPtr dt = + Factory::CreateDrawTargetForCairoSurface(similar, size); // The DT addrefs the surface, so we need drop our own reference to it: cairo_surface_destroy(similar); @@ -152,7 +163,8 @@ already_AddRefed PrintTargetCG::GetReferenceDrawTarget() { return do_AddRef(mRefDT); } -nsresult PrintTargetCG::BeginPrinting(const nsAString& aTitle, const nsAString& aPrintToFileName, +nsresult PrintTargetCG::BeginPrinting(const nsAString& aTitle, + const nsAString& aPrintToFileName, int32_t aStartPage, int32_t aEndPage) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; @@ -182,7 +194,8 @@ nsresult PrintTargetCG::BeginPrinting(const nsAString& aTitle, const nsAString& status = ::PMSetLastPage(mPrintSettings, aEndPage, false); NS_ASSERTION(status == noErr, "PMSetLastPage failed"); - status = ::PMSessionBeginCGDocumentNoDialog(mPrintSession, mPrintSettings, mPageFormat); + status = ::PMSessionBeginCGDocumentNoDialog(mPrintSession, mPrintSettings, + mPageFormat); return status == noErr ? NS_OK : NS_ERROR_ABORT; @@ -224,11 +237,13 @@ nsresult PrintTargetCG::BeginPage(const IntSize& aSizeInPoints) { if (StaticPrefs::layout_css_page_orientation_enabled()) { ::PMOrientation pageOrientation = - aSizeInPoints.width < aSizeInPoints.height ? kPMPortrait : kPMLandscape; + aSizeInPoints.width < aSizeInPoints.height ? kPMPortrait + : kPMLandscape; ::PMSetOrientation(mPageFormat, pageOrientation, kPMUnlocked); // We don't need to reset the orientation, since we set it for every page. } - OSStatus status = ::PMSessionBeginPageNoDialog(mPrintSession, mPageFormat, nullptr); + OSStatus status = + ::PMSessionBeginPageNoDialog(mPrintSession, mPageFormat, nullptr); if (status != noErr) { return NS_ERROR_ABORT; } @@ -257,7 +272,8 @@ nsresult PrintTargetCG::BeginPage(const IntSize& aSizeInPoints) { CGContextTranslateCTM(context, 0, height); CGContextScaleCTM(context, 1.0, -1.0); - cairo_surface_t* surface = cairo_quartz_surface_create_for_cg_context(context, width, height); + cairo_surface_t* surface = + cairo_quartz_surface_create_for_cg_context(context, width, height); if (cairo_surface_status(surface)) { return NS_ERROR_FAILURE; diff --git a/gfx/thebes/gfxMacPlatformFontList.mm b/gfx/thebes/gfxMacPlatformFontList.mm index f8c19c6fe109..108d72719cbe 100644 --- a/gfx/thebes/gfxMacPlatformFontList.mm +++ b/gfx/thebes/gfxMacPlatformFontList.mm @@ -63,8 +63,9 @@ static void GetStringForNSString(const NSString* aSrc, nsAString& aDest) { } static NSString* GetNSStringForString(const nsAString& aSrc) { - return [NSString stringWithCharacters:reinterpret_cast(aSrc.BeginReading()) - length:aSrc.Length()]; + return [NSString + stringWithCharacters:reinterpret_cast(aSrc.BeginReading()) + length:aSrc.Length()]; } #define LOG_FONTLIST(args) \ @@ -77,7 +78,8 @@ static NSString* GetNSStringForString(const nsAString& aSrc) { class gfxMacFontFamily final : public CTFontFamily { public: gfxMacFontFamily(const nsACString& aName, NSFont* aSystemFont) - : CTFontFamily(aName, FontVisibility::Unknown), mForSystemFont(aSystemFont) { + : CTFontFamily(aName, FontVisibility::Unknown), + mForSystemFont(aSystemFont) { // I don't think the system font instance is at much risk of being deleted, // but to be on the safe side let's retain a reference until we're finished // using it for lazy initialization. @@ -88,9 +90,9 @@ class gfxMacFontFamily final : public CTFontFamily { MOZ_REQUIRES(mLock) override; protected: - // If non-null, this is a family representing the system UI font, and should use - // the given NSFont as the basis for initialization as the normal font-manager APIs - // based on family name won't handle it. + // If non-null, this is a family representing the system UI font, and should + // use the given NSFont as the basis for initialization as the normal + // font-manager APIs based on family name won't handle it. NSFont* mForSystemFont = nullptr; }; @@ -99,7 +101,8 @@ void gfxMacFontFamily::FindStyleVariationsLocked(FontInfoData* aFontInfoData) { return; } - AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING("gfxMacFontFamily::FindStyleVariations", LAYOUT, mName); + AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING("gfxMacFontFamily::FindStyleVariations", + LAYOUT, mName); nsAutoreleasePool localPool; @@ -113,12 +116,14 @@ void gfxMacFontFamily::FindStyleVariationsLocked(FontInfoData* aFontInfoData) { nsCocoaUtils::GetStringForNSString(psNameNS, nameUTF16); CopyUTF16toUTF8(nameUTF16, psName); - auto* fe = new CTFontEntry(psName, WeightRange(FontWeight::NORMAL), true, 0.0); + auto* fe = + new CTFontEntry(psName, WeightRange(FontWeight::NORMAL), true, 0.0); // Set the appropriate style, assuming it may not have a variation range. fe->mStyleRange = SlantStyleRange( - ([[aNSFont fontDescriptor] symbolicTraits] & NSFontItalicTrait) ? FontSlantStyle::ITALIC - : FontSlantStyle::NORMAL); + ([[aNSFont fontDescriptor] symbolicTraits] & NSFontItalicTrait) + ? FontSlantStyle::ITALIC + : FontSlantStyle::NORMAL); // Set up weight (and width, if present) ranges. fe->SetupVariationRanges(); @@ -128,7 +133,8 @@ void gfxMacFontFamily::FindStyleVariationsLocked(FontInfoData* aFontInfoData) { addToFamily(mForSystemFont); // See if there is a corresponding italic face, and add it to the family. - NSFont* italicFont = [sFontManager convertFont:mForSystemFont toHaveTrait:NSItalicFontMask]; + NSFont* italicFont = [sFontManager convertFont:mForSystemFont + toHaveTrait:NSItalicFontMask]; if (italicFont != mForSystemFont) { addToFamily(italicFont); } @@ -147,7 +153,8 @@ void gfxMacFontFamily::FindStyleVariationsLocked(FontInfoData* aFontInfoData) { class gfxSingleFaceMacFontFamily final : public gfxFontFamily { public: - gfxSingleFaceMacFontFamily(const nsACString& aName, FontVisibility aVisibility) + gfxSingleFaceMacFontFamily(const nsACString& aName, + FontVisibility aVisibility) : gfxFontFamily(aName, aVisibility) { mFaceNamesInitialized = true; // omit from face name lists } @@ -175,8 +182,9 @@ void gfxSingleFaceMacFontFamily::LocalizedName(nsACString& aLocalizedName) { } gfxFontEntry* fe = mAvailableFonts[0]; - NSFont* font = [NSFont fontWithName:GetNSStringForString(NS_ConvertUTF8toUTF16(fe->Name())) - size:0.0]; + NSFont* font = [NSFont + fontWithName:GetNSStringForString(NS_ConvertUTF8toUTF16(fe->Name())) + size:0.0]; if (font) { NSString* localized = [font displayName]; if (localized) { @@ -191,7 +199,8 @@ void gfxSingleFaceMacFontFamily::LocalizedName(nsACString& aLocalizedName) { aLocalizedName = mName; } -void gfxSingleFaceMacFontFamily::ReadOtherFamilyNames(gfxPlatformFontList* aPlatformFontList) { +void gfxSingleFaceMacFontFamily::ReadOtherFamilyNames( + gfxPlatformFontList* aPlatformFontList) { AutoWriteLock lock(mLock); if (mOtherFamilyNamesInitialized) { return; @@ -209,7 +218,8 @@ void gfxSingleFaceMacFontFamily::ReadOtherFamilyNames(gfxPlatformFontList* aPlat return; } - mHasOtherFamilyNames = ReadOtherFamilyNamesForFace(aPlatformFontList, nameTable, true); + mHasOtherFamilyNames = + ReadOtherFamilyNamesForFace(aPlatformFontList, nameTable, true); mOtherFamilyNamesInitialized = true; } @@ -229,7 +239,8 @@ gfxMacPlatformFontList::gfxMacPlatformFontList() : CoreTextFontList() { gfxFontUtils::GetPrefsFontList("font.single-face-list", mSingleFaceFonts); } -FontVisibility gfxMacPlatformFontList::GetVisibilityForFamily(const nsACString& aName) const { +FontVisibility gfxMacPlatformFontList::GetVisibilityForFamily( + const nsACString& aName) const { if (aName[0] == '.' || aName.LowerCaseEqualsLiteral("lastresort")) { return FontVisibility::Hidden; } @@ -244,7 +255,8 @@ FontVisibility gfxMacPlatformFontList::GetVisibilityForFamily(const nsACString& return FontVisibility::User; } -bool gfxMacPlatformFontList::DeprecatedFamilyIsAvailable(const nsACString& aName) { +bool gfxMacPlatformFontList::DeprecatedFamilyIsAvailable( + const nsACString& aName) { NSString* family = GetNSStringForString(NS_ConvertUTF8toUTF16(aName)); return [[sFontManager availableMembersOfFontFamily:family] count] > 0; } @@ -364,7 +376,8 @@ void gfxMacPlatformFontList::InitSingleFaceList() { // We found the correct face, so create the single-face family record. GenerateFontListKey(aliasName, key); - LOG_FONTLIST(("(fontlist-singleface) family name: %s, key: %s\n", aliasName.get(), key.get())); + LOG_FONTLIST(("(fontlist-singleface) family name: %s, key: %s\n", + aliasName.get(), key.get())); // add only if doesn't exist already if (!mFontFamilies.GetWeak(key)) { @@ -372,13 +385,14 @@ void gfxMacPlatformFontList::InitSingleFaceList() { new gfxSingleFaceMacFontFamily(aliasName, family->Visibility()); // We need a separate font entry, because its family name will // differ from the one we found in the main list. - CTFontEntry* fontEntry = new CTFontEntry(fe->Name(), fe->Weight(), true, - static_cast(fe)->mSizeHint); + CTFontEntry* fontEntry = + new CTFontEntry(fe->Name(), fe->Weight(), true, + static_cast(fe)->mSizeHint); familyEntry->AddFontEntry(fontEntry); familyEntry->SetHasStyles(true); mFontFamilies.InsertOrUpdate(key, std::move(familyEntry)); - LOG_FONTLIST( - ("(fontlist-singleface) added new family: %s, key: %s\n", aliasName.get(), key.get())); + LOG_FONTLIST(("(fontlist-singleface) added new family: %s, key: %s\n", + aliasName.get(), key.get())); } } } @@ -404,12 +418,14 @@ static NSString* GetRealFamilyName(NSFont* aFont) { // Eventually we should move to using CTFontUIFontType constants to identify // system fonts, and eliminate the need to instantiate them (indirectly) from // their postscript names. - AutoCFRelease cgFont = CGFontCreateWithFontName(CFStringRef(psName)); + AutoCFRelease cgFont = + CGFontCreateWithFontName(CFStringRef(psName)); if (!cgFont) { return [aFont familyName]; } - AutoCFRelease ctFont = CTFontCreateWithGraphicsFont(cgFont, 0.0, nullptr, nullptr); + AutoCFRelease ctFont = + CTFontCreateWithGraphicsFont(cgFont, 0.0, nullptr, nullptr); if (!ctFont) { return [aFont familyName]; } @@ -441,7 +457,8 @@ void gfxMacPlatformFontList::InitSystemFontNames() { // the hidden system fonts may be excluded from the font list altogether. if (nsCocoaFeatures::OnCatalinaOrLater()) { // This family will be populated based on the given NSFont. - RefPtr fam = new gfxMacFontFamily(mSystemTextFontFamilyName, sys); + RefPtr fam = + new gfxMacFontFamily(mSystemTextFontFamilyName, sys); if (fam) { nsAutoCString key; GenerateFontListKey(mSystemTextFontFamilyName, key); @@ -465,20 +482,23 @@ void gfxMacPlatformFontList::InitSystemFontNames() { // different system font API's always map to the same family under OSX, so // just assume that and emit a warning if that ever changes NSString* sysFamily = GetRealFamilyName([NSFont systemFontOfSize:0.0]); - if ([sysFamily compare:GetRealFamilyName([NSFont boldSystemFontOfSize:0.0])] != NSOrderedSame || - [sysFamily compare:GetRealFamilyName([NSFont controlContentFontOfSize:0.0])] != + if ([sysFamily compare:GetRealFamilyName([NSFont + boldSystemFontOfSize:0.0])] != NSOrderedSame || + [sysFamily compare:GetRealFamilyName([NSFont + controlContentFontOfSize:0.0])] != NSOrderedSame || + [sysFamily compare:GetRealFamilyName([NSFont menuBarFontOfSize:0.0])] != NSOrderedSame || - [sysFamily compare:GetRealFamilyName([NSFont menuBarFontOfSize:0.0])] != NSOrderedSame || - [sysFamily compare:GetRealFamilyName([NSFont toolTipsFontOfSize:0.0])] != NSOrderedSame) { + [sysFamily compare:GetRealFamilyName([NSFont toolTipsFontOfSize:0.0])] != + NSOrderedSame) { NS_WARNING("system font types map to different font families" " -- please log a bug!!"); } #endif } -FontFamily gfxMacPlatformFontList::GetDefaultFontForPlatform(nsPresContext* aPresContext, - const gfxFontStyle* aStyle, - nsAtom* aLanguage) { +FontFamily gfxMacPlatformFontList::GetDefaultFontForPlatform( + nsPresContext* aPresContext, const gfxFontStyle* aStyle, + nsAtom* aLanguage) { nsAutoreleasePool localPool; NSString* defaultFamily = [[NSFont userFontOfSize:aStyle->size] familyName]; @@ -538,11 +558,14 @@ void gfxMacPlatformFontList::LookupSystemFont(LookAndFeel::FontID aSystemFontID, } NSFontSymbolicTraits traits = [[font fontDescriptor] symbolicTraits]; - aFontStyle.style = (traits & NSFontItalicTrait) ? FontSlantStyle::ITALIC : FontSlantStyle::NORMAL; - aFontStyle.weight = (traits & NSFontBoldTrait) ? FontWeight::BOLD : FontWeight::NORMAL; - aFontStyle.stretch = (traits & NSFontExpandedTrait) ? FontStretch::EXPANDED - : (traits & NSFontCondensedTrait) ? FontStretch::CONDENSED - : FontStretch::NORMAL; + aFontStyle.style = (traits & NSFontItalicTrait) ? FontSlantStyle::ITALIC + : FontSlantStyle::NORMAL; + aFontStyle.weight = + (traits & NSFontBoldTrait) ? FontWeight::BOLD : FontWeight::NORMAL; + aFontStyle.stretch = (traits & NSFontExpandedTrait) ? FontStretch::EXPANDED + : (traits & NSFontCondensedTrait) + ? FontStretch::CONDENSED + : FontStretch::NORMAL; aFontStyle.size = [font pointSize]; aFontStyle.systemFont = true; } diff --git a/hal/cocoa/CocoaSensor.mm b/hal/cocoa/CocoaSensor.mm index 96e00369e8eb..ecc39272dc02 100644 --- a/hal/cocoa/CocoaSensor.mm +++ b/hal/cocoa/CocoaSensor.mm @@ -21,7 +21,8 @@ static io_connect_t sDataPort = IO_OBJECT_NULL; static uint64_t sLastMean = -1; static float LMUvalueToLux(uint64_t aValue) { // Conversion formula from regression. See Bug 793728. - // -3*(10^-27)*x^4 + 2.6*(10^-19)*x^3 + -3.4*(10^-12)*x^2 + 3.9*(10^-5)*x - 0.19 + // -3*(10^-27)*x^4 + 2.6*(10^-19)*x^3 + -3.4*(10^-12)*x^2 + 3.9*(10^-5)*x - + // 0.19 long double powerC4 = 1 / pow((long double)10, 27); long double powerC3 = 1 / pow((long double)10, 19); long double powerC2 = 1 / pow((long double)10, 12); @@ -54,7 +55,8 @@ void UpdateHandler(nsITimer* aTimer, void* aClosure) { uint32_t outputs = 2; uint64_t lightLMU[outputs]; - kr = IOConnectCallMethod(sDataPort, 0, nil, 0, nil, 0, lightLMU, &outputs, nil, 0); + kr = IOConnectCallMethod(sDataPort, 0, nil, 0, nil, 0, lightLMU, &outputs, + nil, 0); if (kr == KERN_SUCCESS) { uint64_t mean = (lightLMU[0] + lightLMU[1]) / 2; if (mean == sLastMean) { @@ -84,8 +86,8 @@ void EnableSensorNotifications(SensorType aSensor) { } } else if (aSensor == SENSOR_LIGHT) { io_service_t serviceObject; - serviceObject = - IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleLMUController")); + serviceObject = IOServiceGetMatchingService( + kIOMasterPortDefault, IOServiceMatching("AppleLMUController")); if (!serviceObject) { return; } @@ -104,14 +106,15 @@ void EnableSensorNotifications(SensorType aSensor) { if (!sUpdateTimer) { CallCreateInstance("@mozilla.org/timer;1", &sUpdateTimer); if (sUpdateTimer) { - sUpdateTimer->InitWithNamedFuncCallback(UpdateHandler, nullptr, DEFAULT_SENSOR_POLL, - nsITimer::TYPE_REPEATING_SLACK, - "hal_impl::UpdateHandler"); + sUpdateTimer->InitWithNamedFuncCallback( + UpdateHandler, nullptr, DEFAULT_SENSOR_POLL, + nsITimer::TYPE_REPEATING_SLACK, "hal_impl::UpdateHandler"); } } } void DisableSensorNotifications(SensorType aSensor) { - if (!sActiveSensors[aSensor] || (aSensor != SENSOR_ACCELERATION && aSensor != SENSOR_LIGHT)) { + if (!sActiveSensors[aSensor] || + (aSensor != SENSOR_ACCELERATION && aSensor != SENSOR_LIGHT)) { return; } diff --git a/hal/cocoa/smslib.mm b/hal/cocoa/smslib.mm index 1a27d404a3f1..c48f6ca86232 100644 --- a/hal/cocoa/smslib.mm +++ b/hal/cocoa/smslib.mm @@ -80,20 +80,21 @@ typedef struct sensorSpec { // // These values came from SeisMaCalibrate calibration reports. In general I've // found the following: -// - All Intel-based SMSs have 250 counts per g, centered on 0, but the signs -// are different (and in one case two axes are swapped) +// - All Intel-based SMSs have 250 counts per g, centered on 0, but the +// signs are different (and in one case two axes are swapped) // - PowerBooks and iBooks all have sensors centered on 0, and reading // 50-53 steps per gravity (but with differing polarities!) -// - PowerBooks and iBooks of the same model all have the same axis polarities +// - PowerBooks and iBooks of the same model all have the same axis +// polarities // - PowerBook and iBook access methods are model- and OS version-specific // // So, the sequence of tests is: -// - Try model-specific access methods. Note that the test is for a match to the -// beginning of the model name, e.g. the record with model name "MacBook" -// matches computer models "MacBookPro1,2" and "MacBook1,1" (and "" +// - Try model-specific access methods. Note that the test is for a match +// to the beginning of the model name, e.g. the record with model name +// "MacBook" matches computer models "MacBookPro1,2" and "MacBook1,1" (and "" // matches any model). -// - If no model-specific record's access fails, then try each model-independent -// access method in order, stopping when one works. +// - If no model-specific record's access fails, then try each +// model-independent access method in order, stopping when one works. static const sensorSpec sensors[] = { // ****** Model-dependent methods ****** // The PowerBook5,6 is one of the G4 models that seems to lose @@ -142,7 +143,8 @@ static const sensorSpec sensors[] = { 5, 40, {{1, 0, 2, 0, 251}, {1, 2, 2, 0, -251}, {1, 4, 2, 0, -251}}}, - // MacBook Pro Core 2 Duo 15" AND 17" with LED backlight, introduced June '07. + // MacBook Pro Core 2 Duo 15" AND 17" with LED backlight, introduced June + // '07. // NOTE! The 17" machines have the signs of their X and Y axes reversed // from this calibration, but there's no clear way to discriminate between // the two machines. @@ -169,7 +171,8 @@ static const sensorSpec sensors[] = { 5, 40, {{1, 0, 2, 0, -251}, {1, 2, 2, 0, -251}, {1, 4, 2, 0, 251}}}, - // This is speculative, based on a single user's report. Looks like the X and Y axes + // This is speculative, based on a single user's report. Looks like the X + // and Y axes // are swapped. This is true for no other known Appple laptop. {"MacBookPro5,3", "SMCMotionSensor", @@ -185,10 +188,18 @@ static const sensorSpec sensors[] = { // ****** Model-independent methods ****** // Seen once with PowerBook6,8 under system 10.3.9; I suspect // other G4-based 10.3.* systems might use this - {"", "IOI2CMotionSensor", 24, 60, {{1, 0, 1, 0, 51.5}, {1, 1, 1, 0, 51.5}, {1, 2, 1, 0, 51.5}}}, + {"", + "IOI2CMotionSensor", + 24, + 60, + {{1, 0, 1, 0, 51.5}, {1, 1, 1, 0, 51.5}, {1, 2, 1, 0, 51.5}}}, // PowerBook5,6 , PowerBook5,7 , PowerBook6,7 , PowerBook6,8 // under OS X 10.4.* - {"", "IOI2CMotionSensor", 21, 60, {{1, 0, 1, 0, 51.5}, {1, 1, 1, 0, 51.5}, {1, 2, 1, 0, 51.5}}}, + {"", + "IOI2CMotionSensor", + 21, + 60, + {{1, 0, 1, 0, 51.5}, {1, 1, 1, 0, 51.5}, {1, 2, 1, 0, 51.5}}}, // PowerBook5,8 , PowerBook5,9 under OS X 10.4.* {"", "PMUMotionSensor", @@ -200,9 +211,11 @@ static const sensorSpec sensors[] = { {1, 0, 1, 0, -51.5}, {1, 1, 1, -6, -51.5}, {1, 2, 1, 0, -51.5}}}, - // All MacBook, MacBookPro models. Hardware (at least on early MacBookPro 15") + // All MacBook, MacBookPro models. Hardware (at least on early MacBookPro + // 15") // is Kionix KXM52-1050 three-axis accelerometer chip. Data is at - // http://kionix.com/Product-Index/product-index.htm. Specific MB and MBP models + // http://kionix.com/Product-Index/product-index.htm. Specific MB and MBP + // models // that use this are: // MacBook1,1 // MacBook2,1 @@ -215,13 +228,18 @@ static const sensorSpec sensors[] = { // MacBookPro1,2 // MacBookPro4,1 // MacBookPro5,5 - {"", "SMCMotionSensor", 5, 40, {{1, 0, 2, 0, 251}, {1, 2, 2, 0, 251}, {1, 4, 2, 0, 251}}}}; + {"", + "SMCMotionSensor", + 5, + 40, + {{1, 0, 2, 0, 251}, {1, 2, 2, 0, 251}, {1, 4, 2, 0, 251}}}}; #define SENSOR_COUNT (sizeof(sensors) / sizeof(sensorSpec)) #pragma mark Internal prototypes -static int getData(sms_acceleration* accel, int calibrated, id logObject, SEL logSelector); +static int getData(sms_acceleration* accel, int calibrated, id logObject, + SEL logSelector); static float getAxis(int which, int calibrated); static int signExtend(int value, int size); static NSString* getModelName(void); @@ -259,7 +277,8 @@ static float onegs[3]; // X, Y and Z one-g calibration values // Name of configuration for given axis' zero (axis specified by integer) #define ZERO_NAME(a) [NSString stringWithFormat:@"%@-Axis-Zero", INT_TO_AXIS(a)] // Name of configuration for given axis' oneg (axis specified by integer) -#define ONEG_NAME(a) [NSString stringWithFormat:@"%@-Axis-One-g", INT_TO_AXIS(a)] +#define ONEG_NAME(a) \ + [NSString stringWithFormat:@"%@-Axis-One-g", INT_TO_AXIS(a)] // Name of "Is calibrated" preference #define CALIBRATED_NAME (@"Calibrated") // Application domain for SeisMac library @@ -271,19 +290,22 @@ static float onegs[3]; // X, Y and Z one-g calibration values if (logObject) { \ [logObject performSelector:logSelector withObject:message]; \ } -#define LOG_ARG(format, var1) \ - if (logObject) { \ - [logObject performSelector:logSelector withObject:[NSString stringWithFormat:format, var1]]; \ +#define LOG_ARG(format, var1) \ + if (logObject) { \ + [logObject performSelector:logSelector \ + withObject:[NSString stringWithFormat:format, var1]]; \ } -#define LOG_2ARG(format, var1, var2) \ - if (logObject) { \ - [logObject performSelector:logSelector \ - withObject:[NSString stringWithFormat:format, var1, var2]]; \ +#define LOG_2ARG(format, var1, var2) \ + if (logObject) { \ + [logObject \ + performSelector:logSelector \ + withObject:[NSString stringWithFormat:format, var1, var2]]; \ } -#define LOG_3ARG(format, var1, var2, var3) \ - if (logObject) { \ - [logObject performSelector:logSelector \ - withObject:[NSString stringWithFormat:format, var1, var2, var3]]; \ +#define LOG_3ARG(format, var1, var2, var3) \ + if (logObject) { \ + [logObject \ + performSelector:logSelector \ + withObject:[NSString stringWithFormat:format, var1, var2, var3]]; \ } #pragma mark Function definitions @@ -322,11 +344,12 @@ int smsStartup(id logObject, SEL logSelector) { recordSize = sensors[sensorNum].recordSize; function = sensors[sensorNum].function; - LOG_3ARG(@"Trying service \"%s\" with selector %d and %d byte record:\n", serviceName, function, - recordSize); + LOG_3ARG(@"Trying service \"%s\" with selector %d and %d byte record:\n", + serviceName, function, recordSize); - NSString* targetName = [NSString stringWithCString:sensors[sensorNum].model - encoding:NSMacOSRomanStringEncoding]; + NSString* targetName = + [NSString stringWithCString:sensors[sensorNum].model + encoding:NSMacOSRomanStringEncoding]; LOG_ARG(@" Comparing model name to target \"%@\": ", targetName); if ([targetName length] == 0 || [modelName hasPrefix:targetName]) { LOG(@"success.\n"); @@ -350,7 +373,8 @@ int smsStartup(id logObject, SEL logSelector) { } LOG(@" Getting list of matching services: "); - result = IOServiceGetMatchingServices(kIOMasterPortDefault, dict, &iterator); + result = + IOServiceGetMatchingServices(kIOMasterPortDefault, dict, &iterator); if (result == KERN_SUCCESS) { LOG(@"success.\n"); @@ -386,7 +410,9 @@ int smsStartup(id logObject, SEL logSelector) { } continue; } else if (connection == 0) { - LOG_ARG(@"'success', but didn't get a connection (return value was: 0x%x).\n", result); + LOG_ARG( + @"'success', but didn't get a connection (return value was: 0x%x).\n", + result); IOObjectRelease(device); if (failure_result < SMS_FAIL_CONNECTION) { failure_result = SMS_FAIL_CONNECTION; @@ -551,14 +577,15 @@ void smsGetBufferData(char* buffer) { #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1050 const size_t InStructSize = recordSize; size_t OutStructSize = recordSize; - result = - IOConnectCallStructMethod(connection, - function, // magic kernel function number - (const void*)iRecord, InStructSize, (void*)buffer, &OutStructSize); + result = IOConnectCallStructMethod(connection, + function, // magic kernel function number + (const void*)iRecord, InStructSize, + (void*)buffer, &OutStructSize); #else // __MAC_OS_X_VERSION_MIN_REQUIRED 1050 - result = IOConnectMethodStructureIStructureO(connection, - function, // magic kernel function number - iSize, &oSize, iRecord, buffer); + result = IOConnectMethodStructureIStructureO( + connection, + function, // magic kernel function number + iSize, &oSize, iRecord, buffer); #endif // __MAC_OS_X_VERSION_MIN_REQUIRED 1050 if (result != KERN_SUCCESS) { @@ -580,9 +607,10 @@ NSString* smsGetCalibrationDescription(void) { [s appendString:@"---- SeisMac Calibration Record ----\n \n"]; [s appendFormat:@"Machine model: %@\n", getModelName()]; [s appendFormat:@"OS X build: %@\n", getOSVersion()]; - [s appendFormat:@"SeisMacLib version %s, record %d\n \n", SMSLIB_VERSION, sensorNum]; - [s appendFormat:@"Using service \"%s\", function index %d, size %d\n \n", serviceName, function, - recordSize]; + [s appendFormat:@"SeisMacLib version %s, record %d\n \n", SMSLIB_VERSION, + sensorNum]; + [s appendFormat:@"Using service \"%s\", function index %d, size %d\n \n", + serviceName, function, recordSize]; if (prefIntRead(CALIBRATED_NAME, &success) && success) { [s appendString:@"Calibration values (from calibration):\n"]; } else { @@ -670,7 +698,8 @@ static void deleteCalibration(void) { static float prefFloatRead(NSString* prefName, BOOL* success) { float result = 0.0f; - CFPropertyListRef ref = CFPreferencesCopyAppValue((CFStringRef)prefName, APP_ID); + CFPropertyListRef ref = + CFPreferencesCopyAppValue((CFStringRef)prefName, APP_ID); // If there isn't such a preference, fail if (ref == NULL) { *success = NO; @@ -682,7 +711,8 @@ static float prefFloatRead(NSString* prefName, BOOL* success) { // Is it a floating point number? if (CFNumberIsFloatType((CFNumberRef)ref)) { // Yup: grab it. - *success = CFNumberGetValue((__CFNumber*)ref, kCFNumberFloat32Type, &result); + *success = + CFNumberGetValue((__CFNumber*)ref, kCFNumberFloat32Type, &result); } else { // Nope: grab as an integer, and convert to a float. long num; @@ -707,7 +737,8 @@ static float prefFloatRead(NSString* prefName, BOOL* success) { // Writes a named floating point value to the stored preferences. static void prefFloatWrite(NSString* prefName, float prefValue) { - CFNumberRef cfFloat = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &prefValue); + CFNumberRef cfFloat = + CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &prefValue); CFPreferencesSetAppValue((CFStringRef)prefName, cfFloat, APP_ID); CFRelease(cfFloat); } @@ -715,7 +746,8 @@ static void prefFloatWrite(NSString* prefName, float prefValue) { // Reads a named integer value from the stored preferences. static int prefIntRead(NSString* prefName, BOOL* success) { Boolean internalSuccess; - CFIndex result = CFPreferencesGetAppIntegerValue((CFStringRef)prefName, APP_ID, &internalSuccess); + CFIndex result = CFPreferencesGetAppIntegerValue((CFStringRef)prefName, + APP_ID, &internalSuccess); *success = internalSuccess; return result; @@ -723,7 +755,8 @@ static int prefIntRead(NSString* prefName, BOOL* success) { // Writes a named integer value to the stored preferences. static void prefIntWrite(NSString* prefName, int prefValue) { - CFPreferencesSetAppValue((CFStringRef)prefName, (CFNumberRef)[NSNumber numberWithInt:prefValue], + CFPreferencesSetAppValue((CFStringRef)prefName, + (CFNumberRef)[NSNumber numberWithInt:prefValue], APP_ID); } @@ -736,7 +769,8 @@ static void prefDelete(NSString* prefName) { static void prefSynchronize(void) { CFPreferencesAppSynchronize(APP_ID); } // Internal version of accelGetData, with logging -int getData(sms_acceleration* accel, int calibrated, id logObject, SEL logSelector) { +int getData(sms_acceleration* accel, int calibrated, id logObject, + SEL logSelector) { IOItemCount iSize = recordSize; IOByteCount oSize = recordSize; kern_return_t result; @@ -754,14 +788,15 @@ int getData(sms_acceleration* accel, int calibrated, id logObject, SEL logSelect #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1050 const size_t InStructSize = recordSize; size_t OutStructSize = recordSize; - result = - IOConnectCallStructMethod(connection, - function, // magic kernel function number - (const void*)iRecord, InStructSize, (void*)oRecord, &OutStructSize); + result = IOConnectCallStructMethod(connection, + function, // magic kernel function number + (const void*)iRecord, InStructSize, + (void*)oRecord, &OutStructSize); #else // __MAC_OS_X_VERSION_MIN_REQUIRED 1050 - result = IOConnectMethodStructureIStructureO(connection, - function, // magic kernel function number - iSize, &oSize, iRecord, oRecord); + result = IOConnectMethodStructureIStructureO( + connection, + function, // magic kernel function number + iSize, &oSize, iRecord, oRecord); #endif // __MAC_OS_X_VERSION_MIN_REQUIRED 1050 if (result != KERN_SUCCESS) { @@ -845,11 +880,13 @@ NSString* getModelName(void) { // Returns the current OS X version and build (e.g. "10.4.7 (build 8J2135a)") NSString* getOSVersion(void) { - NSDictionary* dict = [NSDictionary - dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"]; + NSDictionary* dict = + [NSDictionary dictionaryWithContentsOfFile: + @"/System/Library/CoreServices/SystemVersion.plist"]; NSString* versionString = [dict objectForKey:@"ProductVersion"]; NSString* buildString = [dict objectForKey:@"ProductBuildVersion"]; - NSString* wholeString = [NSString stringWithFormat:@"%@ (build %@)", versionString, buildString]; + NSString* wholeString = + [NSString stringWithFormat:@"%@ (build %@)", versionString, buildString]; return wholeString; } diff --git a/image/decoders/icon/mac/nsIconChannelCocoa.mm b/image/decoders/icon/mac/nsIconChannelCocoa.mm index 8bc4729a224a..61a3cee6d9ee 100644 --- a/image/decoders/icon/mac/nsIconChannelCocoa.mm +++ b/image/decoders/icon/mac/nsIconChannelCocoa.mm @@ -42,7 +42,8 @@ nsIconChannel::~nsIconChannel() { } } -NS_IMPL_ISUPPORTS(nsIconChannel, nsIChannel, nsIRequest, nsIRequestObserver, nsIStreamListener) +NS_IMPL_ISUPPORTS(nsIconChannel, nsIChannel, nsIRequest, nsIRequestObserver, + nsIStreamListener) nsresult nsIconChannel::Init(nsIURI* uri) { NS_ASSERTION(uri, "no uri"); @@ -73,7 +74,8 @@ NS_IMETHODIMP nsIconChannel::GetCanceledReason(nsACString& aReason) { return GetCanceledReasonImpl(aReason); } -NS_IMETHODIMP nsIconChannel::CancelWithReason(nsresult aStatus, const nsACString& aReason) { +NS_IMETHODIMP nsIconChannel::CancelWithReason(nsresult aStatus, + const nsACString& aReason) { return CancelWithReasonImpl(aStatus, aReason); } @@ -121,8 +123,8 @@ nsIconChannel::OnStopRequest(nsIRequest* aRequest, nsresult aStatus) { // nsIStreamListener methods NS_IMETHODIMP -nsIconChannel::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aStream, uint64_t aOffset, - uint32_t aCount) { +nsIconChannel::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aStream, + uint64_t aOffset, uint32_t aCount) { if (mListener) { return mListener->OnDataAvailable(this, aStream, aOffset, aCount); } @@ -156,13 +158,15 @@ nsIconChannel::GetURI(nsIURI** aURI) { NS_IMETHODIMP nsIconChannel::Open(nsIInputStream** _retval) { nsCOMPtr listener; - nsresult rv = nsContentSecurityManager::doContentSecurityCheck(this, listener); + nsresult rv = + nsContentSecurityManager::doContentSecurityCheck(this, listener); NS_ENSURE_SUCCESS(rv, rv); return MakeInputStream(_retval, false); } -nsresult nsIconChannel::ExtractIconInfoFromUrl(nsIFile** aLocalFile, uint32_t* aDesiredImageSize, +nsresult nsIconChannel::ExtractIconInfoFromUrl(nsIFile** aLocalFile, + uint32_t* aDesiredImageSize, nsACString& aContentType, nsACString& aFileExtension) { nsresult rv = NS_OK; @@ -196,18 +200,21 @@ nsresult nsIconChannel::ExtractIconInfoFromUrl(nsIFile** aLocalFile, uint32_t* a NS_IMETHODIMP nsIconChannel::AsyncOpen(nsIStreamListener* aListener) { nsCOMPtr listener = aListener; - nsresult rv = nsContentSecurityManager::doContentSecurityCheck(this, listener); + nsresult rv = + nsContentSecurityManager::doContentSecurityCheck(this, listener); if (NS_FAILED(rv)) { mCallbacks = nullptr; return rv; } - MOZ_ASSERT(mLoadInfo->GetSecurityMode() == 0 || mLoadInfo->GetInitialSecurityCheckDone() || - (mLoadInfo->GetSecurityMode() == - nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL && - mLoadInfo->GetLoadingPrincipal() && - mLoadInfo->GetLoadingPrincipal()->IsSystemPrincipal()), - "security flags in loadInfo but doContentSecurityCheck() not called"); + MOZ_ASSERT( + mLoadInfo->GetSecurityMode() == 0 || + mLoadInfo->GetInitialSecurityCheckDone() || + (mLoadInfo->GetSecurityMode() == + nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL && + mLoadInfo->GetLoadingPrincipal() && + mLoadInfo->GetLoadingPrincipal()->IsSystemPrincipal()), + "security flags in loadInfo but doContentSecurityCheck() not called"); nsCOMPtr inStream; rv = MakeInputStream(getter_AddRefs(inStream), true); @@ -218,7 +225,8 @@ nsIconChannel::AsyncOpen(nsIStreamListener* aListener) { // Init our stream pump nsCOMPtr target = - nsContentUtils::GetEventTargetByLoadInfo(mLoadInfo, mozilla::TaskCategory::Other); + nsContentUtils::GetEventTargetByLoadInfo(mLoadInfo, + mozilla::TaskCategory::Other); rv = mPump->Init(inStream, 0, 0, false, target); if (NS_FAILED(rv)) { mCallbacks = nullptr; @@ -240,15 +248,16 @@ nsIconChannel::AsyncOpen(nsIStreamListener* aListener) { return rv; } -nsresult nsIconChannel::MakeInputStream(nsIInputStream** _retval, bool aNonBlocking) { +nsresult nsIconChannel::MakeInputStream(nsIInputStream** _retval, + bool aNonBlocking) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; nsCString contentType; nsAutoCString fileExt; nsCOMPtr fileloc; // file we want an icon for uint32_t desiredImageSize; - nsresult rv = - ExtractIconInfoFromUrl(getter_AddRefs(fileloc), &desiredImageSize, contentType, fileExt); + nsresult rv = ExtractIconInfoFromUrl(getter_AddRefs(fileloc), + &desiredImageSize, contentType, fileExt); NS_ENSURE_SUCCESS(rv, rv); bool fileExists = false; @@ -265,7 +274,8 @@ nsresult nsIconChannel::MakeInputStream(nsIInputStream** _retval, bool aNonBlock CFURLRef macURL; if (NS_SUCCEEDED(localFileMac->GetCFURL(&macURL))) { - iconImage = [[NSWorkspace sharedWorkspace] iconForFile:[(NSURL*)macURL path]]; + iconImage = + [[NSWorkspace sharedWorkspace] iconForFile:[(NSURL*)macURL path]]; ::CFRelease(macURL); } } @@ -278,7 +288,8 @@ nsresult nsIconChannel::MakeInputStream(nsIInputStream** _retval, bool aNonBlock // If we still don't have an icon, get the generic document icon. if (!iconImage) { - iconImage = [[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeUnknown]; + iconImage = + [[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeUnknown]; } if (!iconImage) { @@ -296,8 +307,10 @@ nsresult nsIconChannel::MakeInputStream(nsIInputStream** _retval, bool aNonBlock // account when it requests these icons; e.g. it will request an icon with // size 16, place it in a 16x16 CSS pixel sized image, and then display it in // a window on a HiDPI screen where the icon now covers 32x32 physical screen - // pixels. So we just always double the size here in order to prevent blurriness. - uint32_t size = (desiredImageSize < 128) ? desiredImageSize * 2 : desiredImageSize; + // pixels. So we just always double the size here in order to prevent + // blurriness. + uint32_t size = + (desiredImageSize < 128) ? desiredImageSize * 2 : desiredImageSize; uint32_t width = size; uint32_t height = size; @@ -322,14 +335,15 @@ nsresult nsIconChannel::MakeInputStream(nsIInputStream** _retval, bool aNonBlock // This gives us the image data in the format we want: BGRA, four bytes per // pixel, in host endianness, with premultiplied alpha. CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); - CGContextRef ctx = - CGBitmapContextCreate(imageBuf, width, height, 8 /* bitsPerComponent */, width * 4, cs, - kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst); + CGContextRef ctx = CGBitmapContextCreate( + imageBuf, width, height, 8 /* bitsPerComponent */, width * 4, cs, + kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(cs); NSGraphicsContext* oldContext = [NSGraphicsContext currentContext]; - [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:ctx - flipped:NO]]; + [NSGraphicsContext + setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:ctx + flipped:NO]]; [iconImage drawInRect:NSMakeRect(0, 0, width, height)]; @@ -340,8 +354,8 @@ nsresult nsIconChannel::MakeInputStream(nsIInputStream** _retval, bool aNonBlock // Now, create a pipe and stuff our data into it nsCOMPtr inStream; nsCOMPtr outStream; - NS_NewPipe(getter_AddRefs(inStream), getter_AddRefs(outStream), bufferCapacity, bufferCapacity, - aNonBlocking); + NS_NewPipe(getter_AddRefs(inStream), getter_AddRefs(outStream), + bufferCapacity, bufferCapacity, aNonBlocking); uint32_t written; rv = outStream->Write((char*)fileBuf.get(), bufferCapacity, &written); @@ -368,10 +382,14 @@ nsIconChannel::SetLoadFlags(uint32_t aLoadAttributes) { } NS_IMETHODIMP -nsIconChannel::GetTRRMode(nsIRequest::TRRMode* aTRRMode) { return GetTRRModeImpl(aTRRMode); } +nsIconChannel::GetTRRMode(nsIRequest::TRRMode* aTRRMode) { + return GetTRRModeImpl(aTRRMode); +} NS_IMETHODIMP -nsIconChannel::SetTRRMode(nsIRequest::TRRMode aTRRMode) { return SetTRRModeImpl(aTRRMode); } +nsIconChannel::SetTRRMode(nsIRequest::TRRMode aTRRMode) { + return SetTRRModeImpl(aTRRMode); +} NS_IMETHODIMP nsIconChannel::GetIsDocument(bool* aIsDocument) { @@ -415,17 +433,20 @@ nsIconChannel::SetContentDisposition(uint32_t aContentDisposition) { } NS_IMETHODIMP -nsIconChannel::GetContentDispositionFilename(nsAString& aContentDispositionFilename) { +nsIconChannel::GetContentDispositionFilename( + nsAString& aContentDispositionFilename) { return NS_ERROR_NOT_AVAILABLE; } NS_IMETHODIMP -nsIconChannel::SetContentDispositionFilename(const nsAString& aContentDispositionFilename) { +nsIconChannel::SetContentDispositionFilename( + const nsAString& aContentDispositionFilename) { return NS_ERROR_NOT_AVAILABLE; } NS_IMETHODIMP -nsIconChannel::GetContentDispositionHeader(nsACString& aContentDispositionHeader) { +nsIconChannel::GetContentDispositionHeader( + nsACString& aContentDispositionHeader) { return NS_ERROR_NOT_AVAILABLE; } @@ -481,14 +502,16 @@ nsIconChannel::SetLoadInfo(nsILoadInfo* aLoadInfo) { } NS_IMETHODIMP -nsIconChannel::GetNotificationCallbacks(nsIInterfaceRequestor** aNotificationCallbacks) { +nsIconChannel::GetNotificationCallbacks( + nsIInterfaceRequestor** aNotificationCallbacks) { *aNotificationCallbacks = mCallbacks.get(); NS_IF_ADDREF(*aNotificationCallbacks); return NS_OK; } NS_IMETHODIMP -nsIconChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aNotificationCallbacks) { +nsIconChannel::SetNotificationCallbacks( + nsIInterfaceRequestor* aNotificationCallbacks) { mCallbacks = aNotificationCallbacks; return NS_OK; } diff --git a/ipc/chromium/src/base/chrome_application_mac.mm b/ipc/chromium/src/base/chrome_application_mac.mm index 4df6df5593b0..405a02a0e744 100644 --- a/ipc/chromium/src/base/chrome_application_mac.mm +++ b/ipc/chromium/src/base/chrome_application_mac.mm @@ -7,7 +7,8 @@ #include "base/logging.h" @interface CrApplication () -@property(readwrite, getter=isHandlingSendEvent, nonatomic) BOOL handlingSendEvent; +@property(readwrite, getter=isHandlingSendEvent, nonatomic) + BOOL handlingSendEvent; @end @implementation CrApplication @@ -19,7 +20,8 @@ + (NSApplication*)sharedApplication { NSApplication* app = [super sharedApplication]; if (![NSApp isKindOfClass:self]) { - CHROMIUM_LOG(ERROR) << "NSApp should be of type " << [[self className] UTF8String] << ", not " + CHROMIUM_LOG(ERROR) << "NSApp should be of type " + << [[self className] UTF8String] << ", not " << [[NSApp className] UTF8String]; DCHECK(false) << "NSApp is of wrong type"; } @@ -59,6 +61,8 @@ ScopedSendingEvent::ScopedSendingEvent() [app_ setHandlingSendEvent:YES]; } -ScopedSendingEvent::~ScopedSendingEvent() { [app_ setHandlingSendEvent:handling_]; } +ScopedSendingEvent::~ScopedSendingEvent() { + [app_ setHandlingSendEvent:handling_]; +} } // namespace chrome_application_mac diff --git a/ipc/chromium/src/base/mac_util.mm b/ipc/chromium/src/base/mac_util.mm index a8564127dfa0..dde8d9a273c7 100644 --- a/ipc/chromium/src/base/mac_util.mm +++ b/ipc/chromium/src/base/mac_util.mm @@ -22,7 +22,8 @@ bool AmIBundled() { if (GetProcessBundleLocation(&psn, &fsref) != noErr) return false; FSCatalogInfo info; - if (FSGetCatalogInfo(&fsref, kFSCatInfoNodeFlags, &info, NULL, NULL, NULL) != noErr) { + if (FSGetCatalogInfo(&fsref, kFSCatInfoNodeFlags, &info, NULL, NULL, NULL) != + noErr) { return false; } diff --git a/ipc/chromium/src/base/message_pump_mac.mm b/ipc/chromium/src/base/message_pump_mac.mm index db6a714052f5..1382e2a0dc40 100644 --- a/ipc/chromium/src/base/message_pump_mac.mm +++ b/ipc/chromium/src/base/message_pump_mac.mm @@ -19,7 +19,8 @@ namespace { void NoOp(void* info) {} -const CFTimeInterval kCFTimeIntervalMax = std::numeric_limits::max(); +const CFTimeInterval kCFTimeIntervalMax = + std::numeric_limits::max(); } // namespace @@ -57,12 +58,13 @@ MessagePumpCFRunLoopBase::MessagePumpCFRunLoopBase() // as needed when ScheduleDelayedWork is called. CFRunLoopTimerContext timer_context = CFRunLoopTimerContext(); timer_context.info = this; - delayed_work_timer_ = CFRunLoopTimerCreate(NULL, // allocator - kCFTimeIntervalMax, // fire time - kCFTimeIntervalMax, // interval - 0, // flags - 0, // priority - RunDelayedWorkTimer, &timer_context); + delayed_work_timer_ = + CFRunLoopTimerCreate(NULL, // allocator + kCFTimeIntervalMax, // fire time + kCFTimeIntervalMax, // interval + 0, // flags + 0, // priority + RunDelayedWorkTimer, &timer_context); CFRunLoopAddTimer(run_loop_, delayed_work_timer_, kCFRunLoopCommonModes); CFRunLoopSourceContext source_context = CFRunLoopSourceContext(); @@ -89,36 +91,42 @@ MessagePumpCFRunLoopBase::MessagePumpCFRunLoopBase() nesting_deferred_work_source_ = CFRunLoopSourceCreate(NULL, // allocator 0, // priority &source_context); - CFRunLoopAddSource(run_loop_, nesting_deferred_work_source_, kCFRunLoopCommonModes); + CFRunLoopAddSource(run_loop_, nesting_deferred_work_source_, + kCFRunLoopCommonModes); CFRunLoopObserverContext observer_context = CFRunLoopObserverContext(); observer_context.info = this; - pre_wait_observer_ = CFRunLoopObserverCreate(NULL, // allocator - kCFRunLoopBeforeWaiting, - true, // repeat - 0, // priority - PreWaitObserver, &observer_context); + pre_wait_observer_ = + CFRunLoopObserverCreate(NULL, // allocator + kCFRunLoopBeforeWaiting, + true, // repeat + 0, // priority + PreWaitObserver, &observer_context); CFRunLoopAddObserver(run_loop_, pre_wait_observer_, kCFRunLoopCommonModes); - pre_source_observer_ = CFRunLoopObserverCreate(NULL, // allocator - kCFRunLoopBeforeSources, - true, // repeat - 0, // priority - PreSourceObserver, &observer_context); + pre_source_observer_ = + CFRunLoopObserverCreate(NULL, // allocator + kCFRunLoopBeforeSources, + true, // repeat + 0, // priority + PreSourceObserver, &observer_context); CFRunLoopAddObserver(run_loop_, pre_source_observer_, kCFRunLoopCommonModes); - enter_exit_observer_ = CFRunLoopObserverCreate(NULL, // allocator - kCFRunLoopEntry | kCFRunLoopExit, - true, // repeat - 0, // priority - EnterExitObserver, &observer_context); + enter_exit_observer_ = + CFRunLoopObserverCreate(NULL, // allocator + kCFRunLoopEntry | kCFRunLoopExit, + true, // repeat + 0, // priority + EnterExitObserver, &observer_context); CFRunLoopAddObserver(run_loop_, enter_exit_observer_, kCFRunLoopCommonModes); - root_power_domain_ = IORegisterForSystemPower( - this, &power_notification_port_, PowerStateNotification, &power_notification_object_); + root_power_domain_ = IORegisterForSystemPower(this, &power_notification_port_, + PowerStateNotification, + &power_notification_object_); if (root_power_domain_ != MACH_PORT_NULL) { - CFRunLoopAddSource(run_loop_, IONotificationPortGetRunLoopSource(power_notification_port_), - kCFRunLoopCommonModes); + CFRunLoopAddSource( + run_loop_, IONotificationPortGetRunLoopSource(power_notification_port_), + kCFRunLoopCommonModes); } } @@ -127,23 +135,27 @@ MessagePumpCFRunLoopBase::MessagePumpCFRunLoopBase() // same number of run loops must be running when this object is destroyed. MessagePumpCFRunLoopBase::~MessagePumpCFRunLoopBase() { if (root_power_domain_ != MACH_PORT_NULL) { - CFRunLoopRemoveSource(run_loop_, IONotificationPortGetRunLoopSource(power_notification_port_), - kCFRunLoopCommonModes); + CFRunLoopRemoveSource( + run_loop_, IONotificationPortGetRunLoopSource(power_notification_port_), + kCFRunLoopCommonModes); IODeregisterForSystemPower(&power_notification_object_); IOServiceClose(root_power_domain_); IONotificationPortDestroy(power_notification_port_); } - CFRunLoopRemoveObserver(run_loop_, enter_exit_observer_, kCFRunLoopCommonModes); + CFRunLoopRemoveObserver(run_loop_, enter_exit_observer_, + kCFRunLoopCommonModes); CFRelease(enter_exit_observer_); - CFRunLoopRemoveObserver(run_loop_, pre_source_observer_, kCFRunLoopCommonModes); + CFRunLoopRemoveObserver(run_loop_, pre_source_observer_, + kCFRunLoopCommonModes); CFRelease(pre_source_observer_); CFRunLoopRemoveObserver(run_loop_, pre_wait_observer_, kCFRunLoopCommonModes); CFRelease(pre_wait_observer_); - CFRunLoopRemoveSource(run_loop_, nesting_deferred_work_source_, kCFRunLoopCommonModes); + CFRunLoopRemoveSource(run_loop_, nesting_deferred_work_source_, + kCFRunLoopCommonModes); CFRelease(nesting_deferred_work_source_); CFRunLoopRemoveSource(run_loop_, idle_work_source_, kCFRunLoopCommonModes); @@ -203,7 +215,8 @@ void MessagePumpCFRunLoopBase::ScheduleWork() { } // Must be called on the run loop thread. -void MessagePumpCFRunLoopBase::ScheduleDelayedWork(const TimeTicks& delayed_work_time) { +void MessagePumpCFRunLoopBase::ScheduleDelayedWork( + const TimeTicks& delayed_work_time) { TimeDelta delta = delayed_work_time - TimeTicks::Now(); delayed_work_fire_time_ = CFAbsoluteTimeGetCurrent() + delta.InSecondsF(); CFRunLoopTimerSetNextFireDate(delayed_work_timer_, delayed_work_fire_time_); @@ -211,7 +224,8 @@ void MessagePumpCFRunLoopBase::ScheduleDelayedWork(const TimeTicks& delayed_work // Called from the run loop. // static -void MessagePumpCFRunLoopBase::RunDelayedWorkTimer(CFRunLoopTimerRef timer, void* info) { +void MessagePumpCFRunLoopBase::RunDelayedWorkTimer(CFRunLoopTimerRef timer, + void* info) { MessagePumpCFRunLoopBase* self = static_cast(info); // The timer won't fire again until it's reset. @@ -392,7 +406,8 @@ void MessagePumpCFRunLoopBase::MaybeScheduleNestingDeferredWork() { // Called from the run loop. // static void MessagePumpCFRunLoopBase::PreWaitObserver(CFRunLoopObserverRef observer, - CFRunLoopActivity activity, void* info) { + CFRunLoopActivity activity, + void* info) { MessagePumpCFRunLoopBase* self = static_cast(info); // Attempt to do some idle work before going to sleep. @@ -408,7 +423,8 @@ void MessagePumpCFRunLoopBase::PreWaitObserver(CFRunLoopObserverRef observer, // Called from the run loop. // static void MessagePumpCFRunLoopBase::PreSourceObserver(CFRunLoopObserverRef observer, - CFRunLoopActivity activity, void* info) { + CFRunLoopActivity activity, + void* info) { MessagePumpCFRunLoopBase* self = static_cast(info); // The run loop has reached the top of the loop and is about to begin @@ -422,7 +438,8 @@ void MessagePumpCFRunLoopBase::PreSourceObserver(CFRunLoopObserverRef observer, // Called from the run loop. // static void MessagePumpCFRunLoopBase::EnterExitObserver(CFRunLoopObserverRef observer, - CFRunLoopActivity activity, void* info) { + CFRunLoopActivity activity, + void* info) { MessagePumpCFRunLoopBase* self = static_cast(info); switch (activity) { @@ -463,7 +480,8 @@ void MessagePumpCFRunLoopBase::EnterExitObserver(CFRunLoopObserverRef observer, // Called from the run loop. // static -void MessagePumpCFRunLoopBase::PowerStateNotification(void* info, io_service_t service, +void MessagePumpCFRunLoopBase::PowerStateNotification(void* info, + io_service_t service, uint32_t message_type, void* message_argument) { // CFRunLoopTimer (NSTimer) is scheduled in terms of CFAbsoluteTime, which @@ -508,7 +526,8 @@ void MessagePumpCFRunLoopBase::PowerStateNotification(void* info, io_service_t s switch (message_type) { case kIOMessageSystemWillPowerOn: if (self->delayed_work_fire_time_ != kCFTimeIntervalMax) { - CFRunLoopTimerSetNextFireDate(self->delayed_work_timer_, self->delayed_work_fire_time_); + CFRunLoopTimerSetNextFireDate(self->delayed_work_timer_, + self->delayed_work_fire_time_); } break; @@ -517,7 +536,8 @@ void MessagePumpCFRunLoopBase::PowerStateNotification(void* info, io_service_t s // The system will wait for 30 seconds before entering sleep if neither // IOAllowPowerChange nor IOCancelPowerChange are called. That would be // pretty antisocial. - IOAllowPowerChange(self->root_power_domain_, reinterpret_cast(message_argument)); + IOAllowPowerChange(self->root_power_domain_, + reinterpret_cast(message_argument)); break; default: @@ -546,7 +566,8 @@ void MessagePumpCFRunLoop::DoRun(Delegate* delegate) { int result; do { MessagePumpScopedAutoreleasePool autorelease_pool(this); - result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, kCFTimeIntervalMax, false); + result = + CFRunLoopRunInMode(kCFRunLoopDefaultMode, kCFTimeIntervalMax, false); } while (result != kCFRunLoopRunStopped && result != kCFRunLoopRunFinished); } @@ -568,7 +589,8 @@ void MessagePumpCFRunLoop::Quit() { // Called by MessagePumpCFRunLoopBase::EnterExitObserver. void MessagePumpCFRunLoop::EnterExitRunLoop(CFRunLoopActivity activity) { - if (activity == kCFRunLoopExit && nesting_level() == run_nesting_level() && quit_pending_) { + if (activity == kCFRunLoopExit && nesting_level() == run_nesting_level() && + quit_pending_) { // Quit was called while loops other than those managed by this object // were running further inside a run loop managed by this object. Now // that all unmanaged inner run loops are gone, stop the loop running @@ -595,7 +617,8 @@ MessagePumpNSRunLoop::~MessagePumpNSRunLoop() { void MessagePumpNSRunLoop::DoRun(Delegate* delegate) { while (keep_running_) { // NSRunLoop manages autorelease pools itself. - [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode + beforeDate:[NSDate distantFuture]]; } keep_running_ = true; diff --git a/ipc/chromium/src/base/platform_thread_mac.mm b/ipc/chromium/src/base/platform_thread_mac.mm index 17cedb0cdbf0..32917ff11e29 100644 --- a/ipc/chromium/src/base/platform_thread_mac.mm +++ b/ipc/chromium/src/base/platform_thread_mac.mm @@ -42,7 +42,9 @@ void InitThreading() { static BOOL multithreaded = [NSThread isMultiThreaded]; if (!multithreaded) { - [NSThread detachNewThreadSelector:@selector(noOp) toTarget:[NoOp class] withObject:nil]; + [NSThread detachNewThreadSelector:@selector(noOp) + toTarget:[NoOp class] + withObject:nil]; multithreaded = YES; DCHECK([NSThread isMultiThreaded]); diff --git a/ipc/chromium/src/base/process_util_mac.mm b/ipc/chromium/src/base/process_util_mac.mm index 04576ee89581..2202c8b65da7 100644 --- a/ipc/chromium/src/base/process_util_mac.mm +++ b/ipc/chromium/src/base/process_util_mac.mm @@ -41,7 +41,8 @@ static mozilla::EnvironmentLog gProcessLog("MOZ_PROCESS_LOG"); namespace base { Result LaunchApp(const std::vector& argv, - const LaunchOptions& options, ProcessHandle* process_handle) { + const LaunchOptions& options, + ProcessHandle* process_handle) { Result retval = Ok(); char* argv_copy[argv.size() + 1]; @@ -52,7 +53,8 @@ Result LaunchApp(const std::vector& argv, EnvironmentArray env_storage; const EnvironmentArray& vars = - options.full_env ? options.full_env : (env_storage = BuildEnvironmentArray(options.env_map)); + options.full_env ? options.full_env + : (env_storage = BuildEnvironmentArray(options.env_map)); posix_spawn_file_actions_t file_actions; int err = posix_spawn_file_actions_init(&file_actions); @@ -60,8 +62,8 @@ Result LaunchApp(const std::vector& argv, DLOG(WARNING) << "posix_spawn_file_actions_init failed"; return Err(LaunchError("posix_spawn_file_actions_init", err)); } - auto file_actions_guard = - mozilla::MakeScopeExit([&file_actions] { posix_spawn_file_actions_destroy(&file_actions); }); + auto file_actions_guard = mozilla::MakeScopeExit( + [&file_actions] { posix_spawn_file_actions_destroy(&file_actions); }); // Turn fds_to_remap array into a set of dup2 calls. // @@ -85,7 +87,8 @@ Result LaunchApp(const std::vector& argv, } if (!options.workdir.empty()) { - int rv = posix_spawn_file_actions_addchdir_np(&file_actions, options.workdir.c_str()); + int rv = posix_spawn_file_actions_addchdir_np(&file_actions, + options.workdir.c_str()); if (rv != 0) { DLOG(WARNING) << "posix_spawn_file_actions_addchdir_np failed"; return Err(LaunchError("posix_spawn_file_actions_addchdir", rv)); @@ -99,15 +102,16 @@ Result LaunchApp(const std::vector& argv, DLOG(WARNING) << "posix_spawnattr_init failed"; return Err(LaunchError("posix_spawnattr_init", err)); } - auto spawnattr_guard = - mozilla::MakeScopeExit([&spawnattr] { posix_spawnattr_destroy(&spawnattr); }); + auto spawnattr_guard = mozilla::MakeScopeExit( + [&spawnattr] { posix_spawnattr_destroy(&spawnattr); }); #if defined(XP_MACOSX) && defined(__aarch64__) if (options.arch == PROCESS_ARCH_X86_64) { cpu_type_t cpu_pref = CPU_TYPE_X86_64; size_t count = 1; size_t ocount = 0; - int rv = posix_spawnattr_setbinpref_np(&spawnattr, count, &cpu_pref, &ocount); + int rv = + posix_spawnattr_setbinpref_np(&spawnattr, count, &cpu_pref, &ocount); if ((rv != 0) || (ocount != count)) { DLOG(WARNING) << "posix_spawnattr_setbinpref_np failed"; return Err(LaunchError("posix_spawnattr_setbinpref_np", rv)); @@ -142,15 +146,16 @@ Result LaunchApp(const std::vector& argv, } int pid = 0; - int spawn_succeeded = - (posix_spawnp(&pid, argv_copy[0], &file_actions, &spawnattr, argv_copy, vars.get()) == 0); + int spawn_succeeded = (posix_spawnp(&pid, argv_copy[0], &file_actions, + &spawnattr, argv_copy, vars.get()) == 0); bool process_handle_valid = pid > 0; if (!spawn_succeeded || !process_handle_valid) { DLOG(WARNING) << "posix_spawnp failed"; retval = Err(LaunchError("posix_spawnp", spawn_succeeded)); } else { - gProcessLog.print("==> process %d launched child process %d\n", GetCurrentProcId(), pid); + gProcessLog.print("==> process %d launched child process %d\n", + GetCurrentProcId(), pid); if (options.wait) HANDLE_EINTR(waitpid(pid, 0, 0)); if (process_handle) *process_handle = pid; @@ -159,7 +164,8 @@ Result LaunchApp(const std::vector& argv, return retval; } -Result LaunchApp(const CommandLine& cl, const LaunchOptions& options, +Result LaunchApp(const CommandLine& cl, + const LaunchOptions& options, ProcessHandle* process_handle) { return LaunchApp(cl.argv(), options, process_handle); } diff --git a/ipc/chromium/src/base/scoped_nsautorelease_pool.mm b/ipc/chromium/src/base/scoped_nsautorelease_pool.mm index 7cbaf8ba632d..174fb821d67e 100644 --- a/ipc/chromium/src/base/scoped_nsautorelease_pool.mm +++ b/ipc/chromium/src/base/scoped_nsautorelease_pool.mm @@ -15,7 +15,9 @@ ScopedNSAutoreleasePool::ScopedNSAutoreleasePool() DCHECK(autorelease_pool_); } -ScopedNSAutoreleasePool::~ScopedNSAutoreleasePool() { [autorelease_pool_ drain]; } +ScopedNSAutoreleasePool::~ScopedNSAutoreleasePool() { + [autorelease_pool_ drain]; +} // Cycle the internal pool, allowing everything there to get cleaned up and // start anew. diff --git a/ipc/chromium/src/base/sys_string_conversions_mac.mm b/ipc/chromium/src/base/sys_string_conversions_mac.mm index 664cec957b74..c33ffef6bc63 100644 --- a/ipc/chromium/src/base/sys_string_conversions_mac.mm +++ b/ipc/chromium/src/base/sys_string_conversions_mac.mm @@ -44,11 +44,12 @@ static StringType CFStringToSTLStringWithEncodingT(CFStringRef cfstring, out_size * sizeof(UInt8) / sizeof(typename StringType::value_type) + 1; std::vector out_buffer(elements); - converted = CFStringGetBytes(cfstring, whole_string, encoding, - 0, // lossByte - false, // isExternalRepresentation - reinterpret_cast(&out_buffer[0]), out_size, - NULL); // usedBufLen + converted = + CFStringGetBytes(cfstring, whole_string, encoding, + 0, // lossByte + false, // isExternalRepresentation + reinterpret_cast(&out_buffer[0]), out_size, + NULL); // usedBufLen if (converted == 0) return StringType(); out_buffer[elements - 1] = '\0'; @@ -61,31 +62,33 @@ static StringType CFStringToSTLStringWithEncodingT(CFStringRef cfstring, // // Do not assert in this function since it is used by the asssertion code! template -static OutStringType STLStringToSTLStringWithEncodingsT(const InStringType& in, - CFStringEncoding in_encoding, - CFStringEncoding out_encoding) { +static OutStringType STLStringToSTLStringWithEncodingsT( + const InStringType& in, CFStringEncoding in_encoding, + CFStringEncoding out_encoding) { typename InStringType::size_type in_length = in.length(); if (in_length == 0) return OutStringType(); scoped_cftyperef cfstring(CFStringCreateWithBytesNoCopy( NULL, reinterpret_cast(in.data()), - in_length * sizeof(typename InStringType::value_type), in_encoding, false, kCFAllocatorNull)); + in_length * sizeof(typename InStringType::value_type), in_encoding, false, + kCFAllocatorNull)); if (!cfstring) return OutStringType(); - return CFStringToSTLStringWithEncodingT(cfstring, out_encoding); + return CFStringToSTLStringWithEncodingT(cfstring, + out_encoding); } // Given an STL string |in| with an encoding specified by |in_encoding|, // return it as a CFStringRef. Returns NULL on failure. template -static CFStringRef STLStringToCFStringWithEncodingsT(const StringType& in, - CFStringEncoding in_encoding) { +static CFStringRef STLStringToCFStringWithEncodingsT( + const StringType& in, CFStringEncoding in_encoding) { typename StringType::size_type in_length = in.length(); if (in_length == 0) return CFSTR(""); - return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast(in.data()), - in_length * sizeof(typename StringType::value_type), in_encoding, - false); + return CFStringCreateWithBytes( + kCFAllocatorDefault, reinterpret_cast(in.data()), + in_length * sizeof(typename StringType::value_type), in_encoding, false); } // Specify the byte ordering explicitly, otherwise CFString will be confused @@ -102,18 +105,22 @@ static const CFStringEncoding kWideStringEncoding = kCFStringEncodingUTF32LE; // Do not assert in this function since it is used by the asssertion code! std::string SysWideToUTF8(const std::wstring& wide) { - return STLStringToSTLStringWithEncodingsT(wide, kWideStringEncoding, - kNarrowStringEncoding); + return STLStringToSTLStringWithEncodingsT( + wide, kWideStringEncoding, kNarrowStringEncoding); } // Do not assert in this function since it is used by the asssertion code! std::wstring SysUTF8ToWide(const StringPiece& utf8) { - return STLStringToSTLStringWithEncodingsT(utf8, kNarrowStringEncoding, - kWideStringEncoding); + return STLStringToSTLStringWithEncodingsT( + utf8, kNarrowStringEncoding, kWideStringEncoding); } -std::string SysWideToNativeMB(const std::wstring& wide) { return SysWideToUTF8(wide); } +std::string SysWideToNativeMB(const std::wstring& wide) { + return SysWideToUTF8(wide); +} -std::wstring SysNativeMBToWide(const StringPiece& native_mb) { return SysUTF8ToWide(native_mb); } +std::wstring SysNativeMBToWide(const StringPiece& native_mb) { + return SysUTF8ToWide(native_mb); +} } // namespace base diff --git a/ipc/glue/MessagePump_mac.mm b/ipc/glue/MessagePump_mac.mm index 2af0e072038c..69b8f1f87ecb 100644 --- a/ipc/glue/MessagePump_mac.mm +++ b/ipc/glue/MessagePump_mac.mm @@ -20,7 +20,8 @@ NS_IMPL_ADDREF_INHERITED(MessagePumpForNonMainUIThreads, MessagePump) NS_IMPL_RELEASE_INHERITED(MessagePumpForNonMainUIThreads, MessagePump) NS_IMPL_QUERY_INTERFACE(MessagePumpForNonMainUIThreads, nsIThreadObserver) -MessagePumpForNonMainUIThreads::MessagePumpForNonMainUIThreads(nsISerialEventTarget* aEventTarget) +MessagePumpForNonMainUIThreads::MessagePumpForNonMainUIThreads( + nsISerialEventTarget* aEventTarget) : mEventTarget(aEventTarget), keep_running_(true) { MOZ_ASSERT(mEventTarget); CFRunLoopSourceContext source_context = CFRunLoopSourceContext(); @@ -36,13 +37,15 @@ MessagePumpForNonMainUIThreads::~MessagePumpForNonMainUIThreads() { CFRelease(quit_source_); } -void MessagePumpForNonMainUIThreads::DoRun(base::MessagePump::Delegate* aDelegate) { - // If this is a chromium thread and no nsThread is associated with it, this call will create a - // new nsThread. +void MessagePumpForNonMainUIThreads::DoRun( + base::MessagePump::Delegate* aDelegate) { + // If this is a chromium thread and no nsThread is associated with it, this + // call will create a new nsThread. nsIThread* thread = NS_GetCurrentThread(); MOZ_ASSERT(thread); - // Set the main thread observer so we can wake up when xpcom events need to get processed. + // Set the main thread observer so we can wake up when xpcom events need to + // get processed. nsCOMPtr ti(do_QueryInterface(thread)); MOZ_ASSERT(ti); ti->SetObserver(this); @@ -63,7 +66,8 @@ void MessagePumpForNonMainUIThreads::DoRun(base::MessagePump::Delegate* aDelegat // Now process the CFRunLoop. It exits after running once. // NSRunLoop manages autorelease pools itself. - [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode + beforeDate:[NSDate distantFuture]]; } ti->SetObserver(nullptr); @@ -77,14 +81,15 @@ void MessagePumpForNonMainUIThreads::Quit() { } NS_IMETHODIMP MessagePumpForNonMainUIThreads::OnDispatchedEvent() { - // ScheduleWork will signal an input source to the run loop, making it exit so it can process the - // xpcom event. + // ScheduleWork will signal an input source to the run loop, making it exit so + // it can process the xpcom event. ScheduleWork(); return NS_OK; } NS_IMETHODIMP -MessagePumpForNonMainUIThreads::OnProcessNextEvent(nsIThreadInternal* thread, bool mayWait) { +MessagePumpForNonMainUIThreads::OnProcessNextEvent(nsIThreadInternal* thread, + bool mayWait) { return NS_OK; } diff --git a/ipc/glue/ProcessUtils_mac.mm b/ipc/glue/ProcessUtils_mac.mm index 0f1d8ecbba68..e850c486aa87 100644 --- a/ipc/glue/ProcessUtils_mac.mm +++ b/ipc/glue/ProcessUtils_mac.mm @@ -25,28 +25,32 @@ void SetThisProcessName(const char* aProcessName) { return; } - NSString* currentName = - [[[NSBundle mainBundle] localizedInfoDictionary] objectForKey:(NSString*)kCFBundleNameKey]; + NSString* currentName = [[[NSBundle mainBundle] localizedInfoDictionary] + objectForKey:(NSString*)kCFBundleNameKey]; char formattedName[1024]; - SprintfLiteral(formattedName, "%s %s", [currentName UTF8String], aProcessName); + SprintfLiteral(formattedName, "%s %s", [currentName UTF8String], + aProcessName); aProcessName = formattedName; - // This function is based on Chrome/Webkit's and relies on potentially dangerous SPI. + // This function is based on Chrome/Webkit's and relies on potentially + // dangerous SPI. typedef CFTypeRef (*LSGetASNType)(); - typedef OSStatus (*LSSetInformationItemType)(int, CFTypeRef, CFStringRef, CFStringRef, - CFDictionaryRef*); + typedef OSStatus (*LSSetInformationItemType)(int, CFTypeRef, CFStringRef, + CFStringRef, CFDictionaryRef*); - CFBundleRef launchServices = ::CFBundleGetBundleWithIdentifier(CFSTR("com.apple.LaunchServices")); + CFBundleRef launchServices = + ::CFBundleGetBundleWithIdentifier(CFSTR("com.apple.LaunchServices")); if (!launchServices) { - NS_WARNING("Failed to set process name: Could not open LaunchServices bundle"); + NS_WARNING( + "Failed to set process name: Could not open LaunchServices bundle"); return; } if (!sApplicationASN) { - sApplicationASN = - ::CFBundleGetFunctionPointerForName(launchServices, CFSTR("_LSGetCurrentApplicationASN")); + sApplicationASN = ::CFBundleGetFunctionPointerForName( + launchServices, CFSTR("_LSGetCurrentApplicationASN")); if (!sApplicationASN) { NS_WARNING("Failed to set process name: Could not get function pointer " "for LaunchServices"); @@ -64,12 +68,13 @@ void SetThisProcessName(const char* aProcessName) { LSSetInformationItemType setInformationItemFunc = reinterpret_cast(sApplicationInfoItem); - void* displayNameKeyAddr = - ::CFBundleGetDataPointerForName(launchServices, CFSTR("_kLSDisplayNameKey")); + void* displayNameKeyAddr = ::CFBundleGetDataPointerForName( + launchServices, CFSTR("_kLSDisplayNameKey")); CFStringRef displayNameKey = nil; if (displayNameKeyAddr) { - displayNameKey = reinterpret_cast(*(CFStringRef*)displayNameKeyAddr); + displayNameKey = + reinterpret_cast(*(CFStringRef*)displayNameKeyAddr); } // We need this to ensure we have a connection to the Process Manager, not @@ -81,20 +86,22 @@ void SetThisProcessName(const char* aProcessName) { CFTypeRef currentAsn = getASNFunc ? getASNFunc() : nullptr; - if (!getASNFunc || !setInformationItemFunc || !displayNameKey || !currentAsn) { + if (!getASNFunc || !setInformationItemFunc || !displayNameKey || + !currentAsn) { NS_WARNING("Failed to set process name: Accessing launchServices failed"); return; } - CFStringRef processName = ::CFStringCreateWithCString(nil, aProcessName, kCFStringEncodingASCII); + CFStringRef processName = + ::CFStringCreateWithCString(nil, aProcessName, kCFStringEncodingASCII); if (!processName) { NS_WARNING("Failed to set process name: Could not create CFStringRef"); return; } - OSErr err = - setInformationItemFunc(UNDOCUMENTED_SESSION_CONSTANT, currentAsn, displayNameKey, processName, - nil); // Optional out param + OSErr err = setInformationItemFunc(UNDOCUMENTED_SESSION_CONSTANT, currentAsn, + displayNameKey, processName, + nil); // Optional out param ::CFRelease(processName); if (err != noErr) { NS_WARNING("Failed to set process name: LSSetInformationItemType err"); diff --git a/ipc/glue/SharedMemoryBasic_mach.mm b/ipc/glue/SharedMemoryBasic_mach.mm index af0d6e624550..b83391763f17 100644 --- a/ipc/glue/SharedMemoryBasic_mach.mm +++ b/ipc/glue/SharedMemoryBasic_mach.mm @@ -71,12 +71,13 @@ bool SharedMemoryBasic::Create(size_t size) { memory_object_size_t memoryObjectSize = round_page(size); - kern_return_t kr = mach_make_memory_entry_64(mach_task_self(), &memoryObjectSize, 0, - MAP_MEM_NAMED_CREATE | VM_PROT_DEFAULT, - getter_Transfers(mPort), MACH_PORT_NULL); + kern_return_t kr = + mach_make_memory_entry_64(mach_task_self(), &memoryObjectSize, 0, + MAP_MEM_NAMED_CREATE | VM_PROT_DEFAULT, + getter_Transfers(mPort), MACH_PORT_NULL); if (kr != KERN_SUCCESS || memoryObjectSize < round_page(size)) { - LOG_ERROR("Failed to make memory entry (%zu bytes). %s (%x)\n", size, mach_error_string(kr), - kr); + LOG_ERROR("Failed to make memory entry (%zu bytes). %s (%x)\n", size, + mach_error_string(kr), kr); CloseHandle(); return false; } @@ -101,12 +102,15 @@ bool SharedMemoryBasic::Map(size_t size, void* fixed_address) { } kr = mach_vm_map(mach_task_self(), &address, round_page(size), 0, - fixed_address ? VM_FLAGS_FIXED : VM_FLAGS_ANYWHERE, mPort.get(), 0, false, - vmProtection, vmProtection, VM_INHERIT_NONE); + fixed_address ? VM_FLAGS_FIXED : VM_FLAGS_ANYWHERE, + mPort.get(), 0, false, vmProtection, vmProtection, + VM_INHERIT_NONE); if (kr != KERN_SUCCESS) { if (!fixed_address) { - LOG_ERROR("Failed to map shared memory (%zu bytes) into %x, port %x. %s (%x)\n", size, - mach_task_self(), mach_port_t(mPort.get()), mach_error_string(kr), kr); + LOG_ERROR( + "Failed to map shared memory (%zu bytes) into %x, port %x. %s (%x)\n", + size, mach_task_self(), mach_port_t(mPort.get()), + mach_error_string(kr), kr); } return false; } @@ -116,7 +120,8 @@ bool SharedMemoryBasic::Map(size_t size, void* fixed_address) { if (kr != KERN_SUCCESS) { LOG_ERROR("Failed to unmap shared memory at unsuitable address " "(%zu bytes) from %x, port %x. %s (%x)\n", - size, mach_task_self(), mach_port_t(mPort.get()), mach_error_string(kr), kr); + size, mach_task_self(), mach_port_t(mPort.get()), + mach_error_string(kr), kr); } return false; } @@ -129,8 +134,9 @@ bool SharedMemoryBasic::Map(size_t size, void* fixed_address) { void* SharedMemoryBasic::FindFreeAddressSpace(size_t size) { mach_vm_address_t address = 0; size = round_page(size); - if (mach_vm_map(mach_task_self(), &address, size, 0, VM_FLAGS_ANYWHERE, MEMORY_OBJECT_NULL, 0, - false, VM_PROT_NONE, VM_PROT_NONE, VM_INHERIT_NONE) != KERN_SUCCESS || + if (mach_vm_map(mach_task_self(), &address, size, 0, VM_FLAGS_ANYWHERE, + MEMORY_OBJECT_NULL, 0, false, VM_PROT_NONE, VM_PROT_NONE, + VM_INHERIT_NONE) != KERN_SUCCESS || vm_deallocate(mach_task_self(), address, size) != KERN_SUCCESS) { return nullptr; } @@ -146,9 +152,11 @@ void SharedMemoryBasic::Unmap() { return; } vm_address_t address = toVMAddress(mMemory); - kern_return_t kr = vm_deallocate(mach_task_self(), address, round_page(mMappedSize)); + kern_return_t kr = + vm_deallocate(mach_task_self(), address, round_page(mMappedSize)); if (kr != KERN_SUCCESS) { - LOG_ERROR("Failed to deallocate shared memory. %s (%x)\n", mach_error_string(kr), kr); + LOG_ERROR("Failed to deallocate shared memory. %s (%x)\n", + mach_error_string(kr), kr); return; } mMemory = nullptr; @@ -161,7 +169,9 @@ void SharedMemoryBasic::CloseHandle() { } } -bool SharedMemoryBasic::IsHandleValid(const Handle& aHandle) const { return aHandle != nullptr; } +bool SharedMemoryBasic::IsHandleValid(const Handle& aHandle) const { + return aHandle != nullptr; +} } // namespace ipc } // namespace mozilla diff --git a/netwerk/system/mac/nsNetworkLinkService.mm b/netwerk/system/mac/nsNetworkLinkService.mm index 146cc97d6dfc..83271c07126f 100644 --- a/netwerk/system/mac/nsNetworkLinkService.mm +++ b/netwerk/system/mac/nsNetworkLinkService.mm @@ -75,7 +75,9 @@ static OSStatus getErrorCodeBool(Boolean success) { } // If given a NULL pointer, return the error code. -static OSStatus getErrorCodePtr(const void* value) { return getErrorCodeBool(value != nullptr); } +static OSStatus getErrorCodePtr(const void* value) { + return getErrorCodeBool(value != nullptr); +} // Convenience function to allow NULL input. static void CFReleaseSafe(CFTypeRef cf) { @@ -86,8 +88,8 @@ static void CFReleaseSafe(CFTypeRef cf) { } } -NS_IMPL_ISUPPORTS(nsNetworkLinkService, nsINetworkLinkService, nsIObserver, nsITimerCallback, - nsINamed) +NS_IMPL_ISUPPORTS(nsNetworkLinkService, nsINetworkLinkService, nsIObserver, + nsITimerCallback, nsINamed) nsNetworkLinkService::nsNetworkLinkService() : mLinkUp(true), @@ -129,7 +131,8 @@ nsNetworkLinkService::GetNetworkID(nsACString& aNetworkID) { } NS_IMETHODIMP -nsNetworkLinkService::GetPlatformDNSIndications(uint32_t* aPlatformDNSIndications) { +nsNetworkLinkService::GetPlatformDNSIndications( + uint32_t* aPlatformDNSIndications) { return NS_ERROR_NOT_IMPLEMENTED; } @@ -139,8 +142,9 @@ void nsNetworkLinkService::GetDnsSuffixListInternal() { auto sendNotification = mozilla::MakeScopeExit([self = RefPtr{this}] { NS_DispatchToMainThread(NS_NewRunnableFunction( - "nsNetworkLinkService::GetDnsSuffixListInternal", - [self]() { self->NotifyObservers(NS_DNS_SUFFIX_LIST_UPDATED_TOPIC, nullptr); })); + "nsNetworkLinkService::GetDnsSuffixListInternal", [self]() { + self->NotifyObservers(NS_DNS_SUFFIX_LIST_UPDATED_TOPIC, nullptr); + })); }); nsTArray result; @@ -176,15 +180,17 @@ nsNetworkLinkService::GetResolvers(nsTArray>& aResolvers) { } NS_IMETHODIMP -nsNetworkLinkService::GetNativeResolvers(nsTArray& aResolvers) { +nsNetworkLinkService::GetNativeResolvers( + nsTArray& aResolvers) { return NS_ERROR_NOT_IMPLEMENTED; } #ifndef SA_SIZE -# define SA_SIZE(sa) \ - ((!(sa) || ((struct sockaddr*)(sa))->sa_len == 0) \ - ? sizeof(uint32_t) \ - : 1 + ((((struct sockaddr*)(sa))->sa_len - 1) | (sizeof(uint32_t) - 1))) +# define SA_SIZE(sa) \ + ((!(sa) || ((struct sockaddr*)(sa))->sa_len == 0) \ + ? sizeof(uint32_t) \ + : 1 + ((((struct sockaddr*)(sa))->sa_len - 1) | \ + (sizeof(uint32_t) - 1))) #endif static bool getMac(struct sockaddr_dl* sdl, char* buf, size_t bufsize) { @@ -196,14 +202,14 @@ static bool getMac(struct sockaddr_dl* sdl, char* buf, size_t bufsize) { return false; } - snprintf(buf, bufsize, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], - mac[5]); + snprintf(buf, bufsize, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], + mac[2], mac[3], mac[4], mac[5]); return true; } /* If the IP matches, get the MAC and return true */ -static bool matchIp(struct sockaddr_dl* sdl, struct sockaddr_inarp* addr, char* ip, char* buf, - size_t bufsize) { +static bool matchIp(struct sockaddr_dl* sdl, struct sockaddr_inarp* addr, + char* ip, char* buf, size_t bufsize) { if (sdl->sdl_alen) { if (!strcmp(inet_ntoa(addr->sin_addr), ip)) { if (getMac(sdl, buf, bufsize)) { @@ -275,8 +281,10 @@ static bool scanArp(char* ip, char* mac, size_t maclen) { struct rt_msghdr* rtm; for (next = &buf[0]; next < lim; next += rtm->rtm_msglen) { rtm = reinterpret_cast(next); - struct sockaddr_inarp* sin2 = reinterpret_cast(rtm + 1); - struct sockaddr_dl* sdl = reinterpret_cast((char*)sin2 + SA_SIZE(sin2)); + struct sockaddr_inarp* sin2 = + reinterpret_cast(rtm + 1); + struct sockaddr_dl* sdl = + reinterpret_cast((char*)sin2 + SA_SIZE(sin2)); if (matchIp(sdl, sin2, ip, mac, maclen)) { return true; } @@ -285,9 +293,10 @@ static bool scanArp(char* ip, char* mac, size_t maclen) { return false; } -// Append the mac address of rtm to `stringsToHash`. If it's not in arp table, append -// ifname and IP address. -static bool parseHashKey(struct rt_msghdr* rtm, nsTArray& stringsToHash, +// Append the mac address of rtm to `stringsToHash`. If it's not in arp table, +// append ifname and IP address. +static bool parseHashKey(struct rt_msghdr* rtm, + nsTArray& stringsToHash, bool skipDstCheck) { struct sockaddr* sa; struct sockaddr_in* sockin; @@ -317,8 +326,8 @@ static bool parseHashKey(struct rt_msghdr* rtm, nsTArray& stringsToHa return false; } - struct sockaddr* gateway = - reinterpret_cast((char*)sa + RTAX_GATEWAY * SA_SIZE(sa)); + struct sockaddr* gateway = reinterpret_cast( + (char*)sa + RTAX_GATEWAY * SA_SIZE(sa)); if (!gateway) { return false; @@ -440,7 +449,8 @@ bool nsNetworkLinkService::RoutingFromKernel(nsTArray& aHash) { sin->sin_addr = mRouteCheckIPv4; if (write(sockfd, rtm, rtm->rtm_msglen) == -1) { - LOG(("RoutingFromKernel: write() failed. No route to the predefine destincation")); + LOG(("RoutingFromKernel: write() failed. No route to the predefine " + "destincation")); return false; } @@ -451,9 +461,11 @@ bool nsNetworkLinkService::RoutingFromKernel(nsTArray& aHash) { return false; } - LOG(("RoutingFromKernel: read() rtm_type: %d (%d), rtm_pid: %d (%d), rtm_seq: %d (%d)\n", + LOG(("RoutingFromKernel: read() rtm_type: %d (%d), rtm_pid: %d (%d), " + "rtm_seq: %d (%d)\n", rtm->rtm_type, RTM_GET, rtm->rtm_pid, pid, rtm->rtm_seq, seq)); - } while (rtm->rtm_type != RTM_GET || rtm->rtm_pid != pid || rtm->rtm_seq != seq); + } while (rtm->rtm_type != RTM_GET || rtm->rtm_pid != pid || + rtm->rtm_seq != seq); return parseHashKey(rtm, aHash, true); } @@ -489,8 +501,9 @@ bool nsNetworkLinkService::IPv4NetworkId(SHA1Sum* aSHA1) { // void nsNetworkLinkService::HashSortedPrefixesAndNetmasks( std::vector prefixAndNetmaskStore, SHA1Sum* sha1) { - // getifaddrs does not guarantee the interfaces will always be in the same order. - // We want to make sure the hash remains consistent Regardless of the interface order. + // getifaddrs does not guarantee the interfaces will always be in the same + // order. We want to make sure the hash remains consistent Regardless of the + // interface order. std::sort(prefixAndNetmaskStore.begin(), prefixAndNetmaskStore.end(), [](prefix_and_netmask a, prefix_and_netmask b) { // compare prefixStore @@ -521,7 +534,8 @@ bool nsNetworkLinkService::IPv6NetworkId(SHA1Sum* sha1) { if ((AF_INET6 == ifa->ifa_addr->sa_family) && !(ifa->ifa_flags & (IFF_POINTOPOINT | IFF_LOOPBACK))) { // only IPv6 interfaces that aren't pointtopoint or loopback - struct sockaddr_in6* sin_netmask = (struct sockaddr_in6*)ifa->ifa_netmask; + struct sockaddr_in6* sin_netmask = + (struct sockaddr_in6*)ifa->ifa_netmask; if (sin_netmask) { struct sockaddr_in6* sin_addr = (struct sockaddr_in6*)ifa->ifa_addr; int scope = net::utils::ipv6_scope(sin_addr->sin6_addr.s6_addr); @@ -530,17 +544,20 @@ bool nsNetworkLinkService::IPv6NetworkId(SHA1Sum* sha1) { memset(&prefix, 0, sizeof(prefix)); // Get the prefix by combining the address and netmask. for (size_t i = 0; i < sizeof(prefix); ++i) { - prefix.s6_addr[i] = - sin_addr->sin6_addr.s6_addr[i] & sin_netmask->sin6_addr.s6_addr[i]; + prefix.s6_addr[i] = sin_addr->sin6_addr.s6_addr[i] & + sin_netmask->sin6_addr.s6_addr[i]; } // check if prefix and netmask was already found - auto prefixAndNetmask = std::make_pair(prefix, sin_netmask->sin6_addr); + auto prefixAndNetmask = + std::make_pair(prefix, sin_netmask->sin6_addr); auto foundPosition = std::find_if( prefixAndNetmaskStore.begin(), prefixAndNetmaskStore.end(), [&prefixAndNetmask](prefix_and_netmask current) { - return memcmp(&prefixAndNetmask.first, ¤t.first, sizeof(in6_addr)) == 0 && - memcmp(&prefixAndNetmask.second, ¤t.second, sizeof(in6_addr)) == 0; + return memcmp(&prefixAndNetmask.first, ¤t.first, + sizeof(in6_addr)) == 0 && + memcmp(&prefixAndNetmask.second, ¤t.second, + sizeof(in6_addr)) == 0; }); if (foundPosition != prefixAndNetmaskStore.end()) { continue; @@ -557,7 +574,8 @@ bool nsNetworkLinkService::IPv6NetworkId(SHA1Sum* sha1) { return false; } - nsNetworkLinkService::HashSortedPrefixesAndNetmasks(prefixAndNetmaskStore, sha1); + nsNetworkLinkService::HashSortedPrefixesAndNetmasks(prefixAndNetmaskStore, + sha1); return true; } @@ -577,15 +595,17 @@ void nsNetworkLinkService::calculateNetworkIdWithDelay(uint32_t aDelay) { return; } - nsCOMPtr target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); + nsCOMPtr target = + do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); if (!target) { return; } - MOZ_ALWAYS_SUCCEEDS( - target->Dispatch(NewRunnableMethod("nsNetworkLinkService::calculateNetworkIdInternal", this, - &nsNetworkLinkService::calculateNetworkIdInternal), - NS_DISPATCH_NORMAL)); + MOZ_ALWAYS_SUCCEEDS(target->Dispatch( + NewRunnableMethod("nsNetworkLinkService::calculateNetworkIdInternal", + this, + &nsNetworkLinkService::calculateNetworkIdInternal), + NS_DISPATCH_NORMAL)); } NS_IMETHODIMP @@ -615,7 +635,8 @@ void nsNetworkLinkService::calculateNetworkIdInternal(void) { SeedNetworkId(sha1); uint8_t digest[SHA1Sum::kHashSize]; sha1.finish(digest); - nsAutoCString newString(reinterpret_cast(digest), SHA1Sum::kHashSize); + nsAutoCString newString(reinterpret_cast(digest), + SHA1Sum::kHashSize); nsresult rv = Base64Encode(newString, output); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); LOG(("networkid: id %s\n", output.get())); @@ -652,16 +673,17 @@ void nsNetworkLinkService::calculateNetworkIdInternal(void) { if (idChanged && !initialIDCalculation) { RefPtr self = this; - NS_DispatchToMainThread( - NS_NewRunnableFunction("nsNetworkLinkService::calculateNetworkIdInternal", - [self]() { self->OnNetworkIdChanged(); })); + NS_DispatchToMainThread(NS_NewRunnableFunction( + "nsNetworkLinkService::calculateNetworkIdInternal", + [self]() { self->OnNetworkIdChanged(); })); } initialIDCalculation = false; } NS_IMETHODIMP -nsNetworkLinkService::Observe(nsISupports* subject, const char* topic, const char16_t* data) { +nsNetworkLinkService::Observe(nsISupports* subject, const char* topic, + const char16_t* data) { if (!strcmp(topic, "xpcom-shutdown")) { Shutdown(); } @@ -671,14 +693,17 @@ nsNetworkLinkService::Observe(nsISupports* subject, const char* topic, const cha /* static */ void nsNetworkLinkService::NetworkConfigChanged(SCDynamicStoreRef aStoreREf, - CFArrayRef aChangedKeys, void* aInfo) { + CFArrayRef aChangedKeys, + void* aInfo) { LOG(("nsNetworkLinkService::NetworkConfigChanged")); bool ipConfigChanged = false; bool dnsConfigChanged = false; for (CFIndex i = 0; i < CFArrayGetCount(aChangedKeys); ++i) { - CFStringRef key = static_cast(CFArrayGetValueAtIndex(aChangedKeys, i)); - if (CFStringHasSuffix(key, kSCEntNetIPv4) || CFStringHasSuffix(key, kSCEntNetIPv6)) { + CFStringRef key = + static_cast(CFArrayGetValueAtIndex(aChangedKeys, i)); + if (CFStringHasSuffix(key, kSCEntNetIPv4) || + CFStringHasSuffix(key, kSCEntNetIPv6)) { ipConfigChanged = true; } if (CFStringHasSuffix(key, kSCEntNetDNS)) { @@ -698,7 +723,8 @@ void nsNetworkLinkService::NetworkConfigChanged(SCDynamicStoreRef aStoreREf, void nsNetworkLinkService::DNSConfigChanged(uint32_t aDelayMs) { LOG(("nsNetworkLinkService::DNSConfigChanged")); - nsCOMPtr target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); + nsCOMPtr target = + do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); if (!target) { return; } @@ -717,9 +743,9 @@ void nsNetworkLinkService::DNSConfigChanged(uint32_t aDelayMs) { "nsNetworkLinkService::GetDnsSuffixListInternal", target)); mDNSConfigChangedTimers.AppendElement(timer); } else { - MOZ_ALWAYS_SUCCEEDS(target->Dispatch( - NS_NewRunnableFunction("nsNetworkLinkService::GetDnsSuffixListInternal", - [self = RefPtr{this}]() { self->GetDnsSuffixListInternal(); }))); + MOZ_ALWAYS_SUCCEEDS(target->Dispatch(NS_NewRunnableFunction( + "nsNetworkLinkService::GetDnsSuffixListInternal", + [self = RefPtr{this}]() { self->GetDnsSuffixListInternal(); }))); } } @@ -745,13 +771,15 @@ nsresult nsNetworkLinkService::Init(void) { bzero(&addr, sizeof(addr)); addr.sin_len = sizeof(addr); addr.sin_family = AF_INET; - mReachability = ::SCNetworkReachabilityCreateWithAddress(nullptr, (struct sockaddr*)&addr); + mReachability = ::SCNetworkReachabilityCreateWithAddress( + nullptr, (struct sockaddr*)&addr); if (!mReachability) { return NS_ERROR_NOT_AVAILABLE; } SCNetworkReachabilityContext context = {0, this, nullptr, nullptr, nullptr}; - if (!::SCNetworkReachabilitySetCallback(mReachability, ReachabilityChanged, &context)) { + if (!::SCNetworkReachabilitySetCallback(mReachability, ReachabilityChanged, + &context)) { NS_WARNING("SCNetworkReachabilitySetCallback failed."); ::CFRelease(mReachability); mReachability = nullptr; @@ -759,24 +787,25 @@ nsresult nsNetworkLinkService::Init(void) { } SCDynamicStoreContext storeContext = {0, this, nullptr, nullptr, nullptr}; - mStoreRef = ::SCDynamicStoreCreate(nullptr, CFSTR("IPAndDNSChangeCallbackSCF"), - NetworkConfigChanged, &storeContext); + mStoreRef = + ::SCDynamicStoreCreate(nullptr, CFSTR("IPAndDNSChangeCallbackSCF"), + NetworkConfigChanged, &storeContext); CFStringRef patterns[4] = {nullptr, nullptr, nullptr, nullptr}; OSStatus err = getErrorCodePtr(mStoreRef); if (err == noErr) { // This pattern is "State:/Network/Service/[^/]+/IPv4". - patterns[0] = ::SCDynamicStoreKeyCreateNetworkServiceEntity(nullptr, kSCDynamicStoreDomainState, - kSCCompAnyRegex, kSCEntNetIPv4); + patterns[0] = ::SCDynamicStoreKeyCreateNetworkServiceEntity( + nullptr, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4); // This pattern is "State:/Network/Service/[^/]+/IPv6". - patterns[1] = ::SCDynamicStoreKeyCreateNetworkServiceEntity(nullptr, kSCDynamicStoreDomainState, - kSCCompAnyRegex, kSCEntNetIPv6); + patterns[1] = ::SCDynamicStoreKeyCreateNetworkServiceEntity( + nullptr, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv6); // This pattern is "State:/Network/Service/[^/]+/DNS". - patterns[2] = ::SCDynamicStoreKeyCreateNetworkServiceEntity(nullptr, kSCDynamicStoreDomainState, - kSCCompAnyRegex, kSCEntNetDNS); + patterns[2] = ::SCDynamicStoreKeyCreateNetworkServiceEntity( + nullptr, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetDNS); // This pattern is "Setup:/Network/Service/[^/]+/DNS". - patterns[3] = ::SCDynamicStoreKeyCreateNetworkServiceEntity(nullptr, kSCDynamicStoreDomainSetup, - kSCCompAnyRegex, kSCEntNetDNS); + patterns[3] = ::SCDynamicStoreKeyCreateNetworkServiceEntity( + nullptr, kSCDynamicStoreDomainSetup, kSCCompAnyRegex, kSCEntNetDNS); if (!patterns[0] || !patterns[1] || !patterns[2] || !patterns[3]) { err = -1; } @@ -788,13 +817,15 @@ nsresult nsNetworkLinkService::Init(void) { // that match that pattern list, then create our run loop // source. if (err == noErr) { - patternList = ::CFArrayCreate(nullptr, (const void**)patterns, 4, &kCFTypeArrayCallBacks); + patternList = ::CFArrayCreate(nullptr, (const void**)patterns, 4, + &kCFTypeArrayCallBacks); if (!patternList) { err = -1; } } if (err == noErr) { - err = getErrorCodeBool(::SCDynamicStoreSetNotificationKeys(mStoreRef, nullptr, patternList)); + err = getErrorCodeBool( + ::SCDynamicStoreSetNotificationKeys(mStoreRef, nullptr, patternList)); } if (err == noErr) { @@ -925,26 +956,31 @@ void nsNetworkLinkService::OnReachabilityChanged() { return; } - NotifyObservers(NS_NETWORK_LINK_TOPIC, - mLinkUp ? NS_NETWORK_LINK_DATA_UP : NS_NETWORK_LINK_DATA_DOWN); + NotifyObservers(NS_NETWORK_LINK_TOPIC, mLinkUp ? NS_NETWORK_LINK_DATA_UP + : NS_NETWORK_LINK_DATA_DOWN); } -void nsNetworkLinkService::NotifyObservers(const char* aTopic, const char* aData) { +void nsNetworkLinkService::NotifyObservers(const char* aTopic, + const char* aData) { MOZ_ASSERT(NS_IsMainThread()); - LOG(("nsNetworkLinkService::NotifyObservers: topic:%s data:%s\n", aTopic, aData ? aData : "")); + LOG(("nsNetworkLinkService::NotifyObservers: topic:%s data:%s\n", aTopic, + aData ? aData : "")); - nsCOMPtr observerService = mozilla::services::GetObserverService(); + nsCOMPtr observerService = + mozilla::services::GetObserverService(); if (observerService) { - observerService->NotifyObservers(static_cast(this), aTopic, - aData ? NS_ConvertASCIItoUTF16(aData).get() : nullptr); + observerService->NotifyObservers( + static_cast(this), aTopic, + aData ? NS_ConvertASCIItoUTF16(aData).get() : nullptr); } } /* static */ void nsNetworkLinkService::ReachabilityChanged(SCNetworkReachabilityRef target, - SCNetworkConnectionFlags flags, void* info) { + SCNetworkConnectionFlags flags, + void* info) { LOG(("nsNetworkLinkService::ReachabilityChanged")); nsNetworkLinkService* service = static_cast(info); diff --git a/netwerk/wifi/mac/MacWifiScanner.mm b/netwerk/wifi/mac/MacWifiScanner.mm index eea0a8162778..9fdccf6c4927 100644 --- a/netwerk/wifi/mac/MacWifiScanner.mm +++ b/netwerk/wifi/mac/MacWifiScanner.mm @@ -29,7 +29,8 @@ nsresult WifiScannerImpl::GetAccessPointsFromWLAN( @try { NSBundle* bundle = [[[NSBundle alloc] - initWithPath:@"/System/Library/Frameworks/CoreWLAN.framework"] autorelease]; + initWithPath:@"/System/Library/Frameworks/CoreWLAN.framework"] + autorelease]; if (!bundle) { [pool release]; return NS_ERROR_NOT_AVAILABLE; @@ -41,7 +42,8 @@ nsresult WifiScannerImpl::GetAccessPointsFromWLAN( return NS_ERROR_NOT_AVAILABLE; } - id scanResult = [[CWI_class interface] scanForNetworksWithSSID:nil error:nil]; + id scanResult = [[CWI_class interface] scanForNetworksWithSSID:nil + error:nil]; if (!scanResult) { [pool release]; return NS_ERROR_NOT_AVAILABLE; @@ -73,7 +75,8 @@ nsresult WifiScannerImpl::GetAccessPointsFromWLAN( NSString* macString = [anObject bssid]; if (macString && ([macString length] == 17)) { for (NSUInteger i = 0; i < 6; ++i) { - NSString* part = [macString substringWithRange:NSMakeRange(i * 3, 2)]; + NSString* part = + [macString substringWithRange:NSMakeRange(i * 3, 2)]; NSScanner* scanner = [NSScanner scannerWithString:part]; unsigned int data = 0; if (![scanner scanHexInt:&data]) { diff --git a/security/manager/ssl/OSReauthenticatorDarwin.mm b/security/manager/ssl/OSReauthenticatorDarwin.mm index ac1ff66f9bcd..5776f6067436 100644 --- a/security/manager/ssl/OSReauthenticatorDarwin.mm +++ b/security/manager/ssl/OSReauthenticatorDarwin.mm @@ -35,12 +35,15 @@ nsresult ReauthenticateUserMacOS(const nsAString& aPrompt, localizedReason:prompt reply:^(BOOL success, NSError* error) { dispatch_async(dispatch_get_main_queue(), ^{ - // error is not particularly useful in this context, and we have no - // mechanism to really return it. We could use it to set the nsresult, - // but this is a best-effort mechanism and there's no particular case for - // propagating up XPCOM. The one exception being a user account that - // has no passcode set, which we handle below. - errorPasswordNotSet = error && [error code] == kPasswordNotSetErrorCode; + // error is not particularly useful in this context, and + // we have no mechanism to really return it. We could + // use it to set the nsresult, but this is a best-effort + // mechanism and there's no particular case for + // propagating up XPCOM. The one exception being a user + // account that has no passcode set, which we handle + // below. + errorPasswordNotSet = + error && [error code] == kPasswordNotSetErrorCode; biometricSuccess = success || errorPasswordNotSet; dispatch_semaphore_signal(sema); }); diff --git a/security/sandbox/mac/Sandbox.mm b/security/sandbox/mac/Sandbox.mm index 24589eb00f89..2c9972a8fa27 100644 --- a/security/sandbox/mac/Sandbox.mm +++ b/security/sandbox/mac/Sandbox.mm @@ -33,7 +33,8 @@ // Undocumented sandbox setup routines. extern "C" int sandbox_init_with_parameters(const char* profile, uint64_t flags, - const char* const parameters[], char** errorbuf); + const char* const parameters[], + char** errorbuf); extern "C" void sandbox_free_error(char* errorbuf); extern "C" int sandbox_check(pid_t pid, const char* operation, int type, ...); @@ -50,7 +51,8 @@ class OSXVersion { static void Get(int32_t& aMajor, int32_t& aMinor); private: - static void GetSystemVersion(int32_t& aMajor, int32_t& aMinor, int32_t& aBugFix); + static void GetSystemVersion(int32_t& aMajor, int32_t& aMinor, + int32_t& aBugFix); static bool mCached; static int32_t mOSXVersionMajor; static int32_t mOSXVersionMinor; @@ -72,23 +74,26 @@ void OSXVersion::Get(int32_t& aMajor, int32_t& aMinor) { aMinor = mOSXVersionMinor; } -void OSXVersion::GetSystemVersion(int32_t& aMajor, int32_t& aMinor, int32_t& aBugFix) { +void OSXVersion::GetSystemVersion(int32_t& aMajor, int32_t& aMinor, + int32_t& aBugFix) { SInt32 major = 0, minor = 0, bugfix = 0; CFURLRef url = CFURLCreateWithString( - kCFAllocatorDefault, CFSTR("file:///System/Library/CoreServices/SystemVersion.plist"), NULL); + kCFAllocatorDefault, + CFSTR("file:///System/Library/CoreServices/SystemVersion.plist"), NULL); CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url); CFReadStreamOpen(stream); - CFDictionaryRef sysVersionPlist = (CFDictionaryRef)CFPropertyListCreateWithStream( - kCFAllocatorDefault, stream, 0, kCFPropertyListImmutable, NULL, NULL); + CFDictionaryRef sysVersionPlist = + (CFDictionaryRef)CFPropertyListCreateWithStream( + kCFAllocatorDefault, stream, 0, kCFPropertyListImmutable, NULL, NULL); CFReadStreamClose(stream); CFRelease(stream); CFRelease(url); - CFStringRef versionString = - (CFStringRef)CFDictionaryGetValue(sysVersionPlist, CFSTR("ProductVersion")); - CFArrayRef versions = - CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, versionString, CFSTR(".")); + CFStringRef versionString = (CFStringRef)CFDictionaryGetValue( + sysVersionPlist, CFSTR("ProductVersion")); + CFArrayRef versions = CFStringCreateArrayBySeparatingStrings( + kCFAllocatorDefault, versionString, CFSTR(".")); CFIndex count = CFArrayGetCount(versions); if (count > 0) { CFStringRef component = (CFStringRef)CFArrayGetValueAtIndex(versions, 0); @@ -188,22 +193,26 @@ void MacSandboxInfo::AppendAsParams(std::vector& aParams) const { } } -void MacSandboxInfo::AppendStartupParam(std::vector& aParams) const { +void MacSandboxInfo::AppendStartupParam( + std::vector& aParams) const { aParams.push_back("-sbStartup"); } -void MacSandboxInfo::AppendLoggingParam(std::vector& aParams) const { +void MacSandboxInfo::AppendLoggingParam( + std::vector& aParams) const { if (this->shouldLog) { aParams.push_back("-sbLogging"); } } -void MacSandboxInfo::AppendAppPathParam(std::vector& aParams) const { +void MacSandboxInfo::AppendAppPathParam( + std::vector& aParams) const { aParams.push_back("-sbAppPath"); aParams.push_back(this->appPath); } -void MacSandboxInfo::AppendPluginPathParam(std::vector& aParams) const { +void MacSandboxInfo::AppendPluginPathParam( + std::vector& aParams) const { aParams.push_back("-sbPluginPath"); aParams.push_back(this->pluginPath); } @@ -230,13 +239,15 @@ void MacSandboxInfo::AppendAudioParam(std::vector& aParams) const { } } -void MacSandboxInfo::AppendWindowServerParam(std::vector& aParams) const { +void MacSandboxInfo::AppendWindowServerParam( + std::vector& aParams) const { if (this->hasWindowServer) { aParams.push_back("-sbAllowWindowServer"); } } -void MacSandboxInfo::AppendReadPathParams(std::vector& aParams) const { +void MacSandboxInfo::AppendReadPathParams( + std::vector& aParams) const { if (!this->testingReadPath1.empty()) { aParams.push_back("-sbTestingReadPath"); aParams.push_back(this->testingReadPath1.c_str()); @@ -256,7 +267,8 @@ void MacSandboxInfo::AppendReadPathParams(std::vector& aParams) con } #ifdef DEBUG -void MacSandboxInfo::AppendDebugWriteDirParam(std::vector& aParams) const { +void MacSandboxInfo::AppendDebugWriteDirParam( + std::vector& aParams) const { if (!this->debugWriteDir.empty()) { aParams.push_back("-sbDebugWriteDir"); aParams.push_back(this->debugWriteDir.c_str()); @@ -430,7 +442,8 @@ bool StartMacSandbox(MacSandboxInfo const& aInfo, std::string& aErrorMessage) { profile.append(SandboxPolicyContentAudioAddend); } } else { - fprintf(stderr, "Content sandbox disabled due to sandbox level setting\n"); + fprintf(stderr, + "Content sandbox disabled due to sandbox level setting\n"); return false; } } else { @@ -465,7 +478,8 @@ bool StartMacSandbox(MacSandboxInfo const& aInfo, std::string& aErrorMessage) { params.push_back(nullptr); char* errorbuf = NULL; - int rv = sandbox_init_with_parameters(profile.c_str(), 0, params.data(), &errorbuf); + int rv = sandbox_init_with_parameters(profile.c_str(), 0, params.data(), + &errorbuf); if (rv) { if (errorbuf) { char* msg = NULL; @@ -490,7 +504,8 @@ bool StartMacSandbox(MacSandboxInfo const& aInfo, std::string& aErrorMessage) { * command line arguments. Return false if any sandbox parameters needed * for early startup of the sandbox are not present in the arguments. */ -bool GetContentSandboxParamsFromArgs(int aArgc, char** aArgv, MacSandboxInfo& aInfo) { +bool GetContentSandboxParamsFromArgs(int aArgc, char** aArgv, + MacSandboxInfo& aInfo) { // Ensure we find these paramaters in the command // line arguments. Return false if any are missing. bool foundSandboxLevel = false; @@ -604,7 +619,8 @@ bool GetContentSandboxParamsFromArgs(int aArgc, char** aArgv, MacSandboxInfo& aI return true; } -bool GetUtilitySandboxParamsFromArgs(int aArgc, char** aArgv, MacSandboxInfo& aInfo, +bool GetUtilitySandboxParamsFromArgs(int aArgc, char** aArgv, + MacSandboxInfo& aInfo, bool aSandboxingKindRequired = true) { // Ensure we find these paramaters in the command // line arguments. Return false if any are missing. @@ -650,11 +666,13 @@ bool GetUtilitySandboxParamsFromArgs(int aArgc, char** aArgv, MacSandboxInfo& aI return true; } -bool GetSocketSandboxParamsFromArgs(int aArgc, char** aArgv, MacSandboxInfo& aInfo) { +bool GetSocketSandboxParamsFromArgs(int aArgc, char** aArgv, + MacSandboxInfo& aInfo) { return GetUtilitySandboxParamsFromArgs(aArgc, aArgv, aInfo, false); } -bool GetPluginSandboxParamsFromArgs(int aArgc, char** aArgv, MacSandboxInfo& aInfo) { +bool GetPluginSandboxParamsFromArgs(int aArgc, char** aArgv, + MacSandboxInfo& aInfo) { // Ensure we find these paramaters in the command // line arguments. Return false if any are missing. bool foundAppPath = false; @@ -725,7 +743,8 @@ bool GetPluginSandboxParamsFromArgs(int aArgc, char** aArgv, MacSandboxInfo& aIn return true; } -bool GetRDDSandboxParamsFromArgs(int aArgc, char** aArgv, MacSandboxInfo& aInfo) { +bool GetRDDSandboxParamsFromArgs(int aArgc, char** aArgv, + MacSandboxInfo& aInfo) { return GetUtilitySandboxParamsFromArgs(aArgc, aArgv, aInfo, false); } @@ -733,8 +752,8 @@ bool GetRDDSandboxParamsFromArgs(int aArgc, char** aArgv, MacSandboxInfo& aInfo) * Returns true if no errors were encountered or if early sandbox startup is * not enabled for this process. Returns false if an error was encountered. */ -bool StartMacSandboxIfEnabled(const MacSandboxType aSandboxType, int aArgc, char** aArgv, - std::string& aErrorMessage) { +bool StartMacSandboxIfEnabled(const MacSandboxType aSandboxType, int aArgc, + char** aArgv, std::string& aErrorMessage) { bool earlyStartupEnabled = false; // Check for the -sbStartup CLI parameter which @@ -796,7 +815,9 @@ bool IsMacSandboxStarted() { return sandbox_check(getpid(), NULL, 0) == 1; } #ifdef DEBUG // sandbox_check returns 1 if the specified process is sandboxed -void AssertMacSandboxEnabled() { MOZ_ASSERT(sandbox_check(getpid(), NULL, 0) == 1); } +void AssertMacSandboxEnabled() { + MOZ_ASSERT(sandbox_check(getpid(), NULL, 0) == 1); +} #endif /* DEBUG */ } // namespace mozilla diff --git a/toolkit/components/parentalcontrols/nsParentalControlsServiceCocoa.mm b/toolkit/components/parentalcontrols/nsParentalControlsServiceCocoa.mm index a2ddb258ff43..d7ef9e48c71b 100644 --- a/toolkit/components/parentalcontrols/nsParentalControlsServiceCocoa.mm +++ b/toolkit/components/parentalcontrols/nsParentalControlsServiceCocoa.mm @@ -12,8 +12,8 @@ NS_IMPL_ISUPPORTS(nsParentalControlsService, nsIParentalControlsService) nsParentalControlsService::nsParentalControlsService() : mEnabled(false) { - mEnabled = CFPreferencesAppValueIsForced(CFSTR("restrictWeb"), - CFSTR("com.apple.familycontrols.contentfilter")); + mEnabled = CFPreferencesAppValueIsForced( + CFSTR("restrictWeb"), CFSTR("com.apple.familycontrols.contentfilter")); } nsParentalControlsService::~nsParentalControlsService() {} @@ -37,13 +37,14 @@ nsParentalControlsService::GetLoggingEnabled(bool* aResult) { } NS_IMETHODIMP -nsParentalControlsService::Log(int16_t aEntryType, bool blocked, nsIURI* aSource, - nsIFile* aTarget) { +nsParentalControlsService::Log(int16_t aEntryType, bool blocked, + nsIURI* aSource, nsIFile* aTarget) { // silently drop on the floor return NS_OK; } NS_IMETHODIMP -nsParentalControlsService::IsAllowed(int16_t aAction, nsIURI* aUri, bool* _retval) { +nsParentalControlsService::IsAllowed(int16_t aAction, nsIURI* aUri, + bool* _retval) { return NS_ERROR_NOT_AVAILABLE; } diff --git a/toolkit/components/processtools/ProcInfo.mm b/toolkit/components/processtools/ProcInfo.mm index 80804aea42e6..6c98ce81f5f5 100644 --- a/toolkit/components/processtools/ProcInfo.mm +++ b/toolkit/components/processtools/ProcInfo.mm @@ -31,7 +31,8 @@ namespace mozilla { nsresult GetCpuTimeSinceProcessStartInMs(uint64_t* aResult) { struct proc_taskinfo pti; - if ((unsigned long)proc_pidinfo(getpid(), PROC_PIDTASKINFO, 0, &pti, PROC_PIDTASKINFO_SIZE) < + if ((unsigned long)proc_pidinfo(getpid(), PROC_PIDTASKINFO, 0, &pti, + PROC_PIDTASKINFO_SIZE) < PROC_PIDTASKINFO_SIZE) { return NS_ERROR_FAILURE; } @@ -39,16 +40,16 @@ nsresult GetCpuTimeSinceProcessStartInMs(uint64_t* aResult) { mach_timebase_info_data_t timebase; GetTimeBase(&timebase); - *aResult = (pti.pti_total_user + pti.pti_total_system) * timebase.numer / timebase.denom / - PR_NSEC_PER_MSEC; + *aResult = (pti.pti_total_user + pti.pti_total_system) * timebase.numer / + timebase.denom / PR_NSEC_PER_MSEC; return NS_OK; } nsresult GetGpuTimeSinceProcessStartInMs(uint64_t* aResult) { task_power_info_v2_data_t task_power_info; mach_msg_type_number_t count = TASK_POWER_INFO_V2_COUNT; - kern_return_t kr = - task_info(mach_task_self(), TASK_POWER_INFO_V2, (task_info_t)&task_power_info, &count); + kern_return_t kr = task_info(mach_task_self(), TASK_POWER_INFO_V2, + (task_info_t)&task_power_info, &count); if (kr != KERN_SUCCESS) { return NS_ERROR_FAILURE; } @@ -59,7 +60,8 @@ nsresult GetGpuTimeSinceProcessStartInMs(uint64_t* aResult) { int GetCycleTimeFrequencyMHz() { return 0; } -ProcInfoPromise::ResolveOrRejectValue GetProcInfoSync(nsTArray&& aRequests) { +ProcInfoPromise::ResolveOrRejectValue GetProcInfoSync( + nsTArray&& aRequests) { ProcInfoPromise::ResolveOrRejectValue result; HashMap gathered; @@ -81,14 +83,16 @@ ProcInfoPromise::ResolveOrRejectValue GetProcInfoSync(nsTArray& info.utilityActors = std::move(request.utilityInfo); struct proc_taskinfo pti; - if ((unsigned long)proc_pidinfo(request.pid, PROC_PIDTASKINFO, 0, &pti, PROC_PIDTASKINFO_SIZE) < + if ((unsigned long)proc_pidinfo(request.pid, PROC_PIDTASKINFO, 0, &pti, + PROC_PIDTASKINFO_SIZE) < PROC_PIDTASKINFO_SIZE) { // Can't read data for this process. // Probably either a sandboxing issue or a race condition, e.g. // the process has been just been killed. Regardless, skip process. continue; } - info.cpuTime = (pti.pti_total_user + pti.pti_total_system) * timebase.numer / timebase.denom; + info.cpuTime = (pti.pti_total_user + pti.pti_total_system) * + timebase.numer / timebase.denom; mach_port_t selectedTask; // If we did not get a task from a child process, we use mach_task_self() @@ -102,7 +106,8 @@ ProcInfoPromise::ResolveOrRejectValue GetProcInfoSync(nsTArray& // matches the value in the 'Memory' column of the Activity Monitor. task_vm_info_data_t task_vm_info; mach_msg_type_number_t count = TASK_VM_INFO_COUNT; - kern_return_t kr = task_info(selectedTask, TASK_VM_INFO, (task_info_t)&task_vm_info, &count); + kern_return_t kr = task_info(selectedTask, TASK_VM_INFO, + (task_info_t)&task_vm_info, &count); info.memory = kr == KERN_SUCCESS ? task_vm_info.phys_footprint : 0; // Now getting threads info @@ -123,8 +128,8 @@ ProcInfoPromise::ResolveOrRejectValue GetProcInfoSync(nsTArray& } // Deallocate the thread list. - // Note that this deallocation is entirely undocumented, so the following code is based - // on guesswork and random examples found on the web. + // Note that this deallocation is entirely undocumented, so the following + // code is based on guesswork and random examples found on the web. auto guardThreadCount = MakeScopeExit([&] { if (threadList == nullptr) { return; @@ -141,8 +146,8 @@ ProcInfoPromise::ResolveOrRejectValue GetProcInfoSync(nsTArray& // Basic thread info. thread_extended_info_data_t threadInfoData; count = THREAD_EXTENDED_INFO_COUNT; - kret = - thread_info(threadList[i], THREAD_EXTENDED_INFO, (thread_info_t)&threadInfoData, &count); + kret = thread_info(threadList[i], THREAD_EXTENDED_INFO, + (thread_info_t)&threadInfoData, &count); if (kret != KERN_SUCCESS) { continue; } @@ -150,8 +155,8 @@ ProcInfoPromise::ResolveOrRejectValue GetProcInfoSync(nsTArray& // Getting the thread id. thread_identifier_info identifierInfo; count = THREAD_IDENTIFIER_INFO_COUNT; - kret = thread_info(threadList[i], THREAD_IDENTIFIER_INFO, (thread_info_t)&identifierInfo, - &count); + kret = thread_info(threadList[i], THREAD_IDENTIFIER_INFO, + (thread_info_t)&identifierInfo, &count); if (kret != KERN_SUCCESS) { continue; } @@ -162,7 +167,8 @@ ProcInfoPromise::ResolveOrRejectValue GetProcInfoSync(nsTArray& result.SetReject(NS_ERROR_OUT_OF_MEMORY); return result; } - thread->cpuTime = threadInfoData.pth_user_time + threadInfoData.pth_system_time; + thread->cpuTime = + threadInfoData.pth_user_time + threadInfoData.pth_system_time; thread->name.AssignASCII(threadInfoData.pth_name); thread->tid = identifierInfo.thread_id; } diff --git a/toolkit/components/remote/nsMacRemoteClient.mm b/toolkit/components/remote/nsMacRemoteClient.mm index 314eebc030e8..aa93d1f3e8f3 100644 --- a/toolkit/components/remote/nsMacRemoteClient.mm +++ b/toolkit/components/remote/nsMacRemoteClient.mm @@ -18,21 +18,21 @@ using namespace mozilla; nsresult nsMacRemoteClient::Init() { return NS_OK; } -nsresult nsMacRemoteClient::SendCommandLine(const char* aProgram, const char* aProfile, - int32_t argc, char** argv, - const char* aDesktopStartupID, char** aResponse, - bool* aSucceeded) { +nsresult nsMacRemoteClient::SendCommandLine( + const char* aProgram, const char* aProfile, int32_t argc, char** argv, + const char* aDesktopStartupID, char** aResponse, bool* aSucceeded) { mozilla::MacAutoreleasePool pool; *aSucceeded = false; nsString className; BuildClassName(aProgram, aProfile, className); - NSString* serverNameString = - [NSString stringWithCharacters:reinterpret_cast(className.get()) - length:className.Length()]; + NSString* serverNameString = [NSString + stringWithCharacters:reinterpret_cast(className.get()) + length:className.Length()]; - CFMessagePortRef messageServer = CFMessagePortCreateRemote(0, (CFStringRef)serverNameString); + CFMessagePortRef messageServer = + CFMessagePortCreateRemote(0, (CFStringRef)serverNameString); if (messageServer) { // Getting current process directory @@ -48,7 +48,8 @@ nsresult nsMacRemoteClient::SendCommandLine(const char* aProgram, const char* aP NSData* data = [NSKeyedArchiver archivedDataWithRootObject:dict]; - CFMessagePortSendRequest(messageServer, 0, (CFDataRef)data, 10.0, 0.0, NULL, NULL); + CFMessagePortSendRequest(messageServer, 0, (CFDataRef)data, 10.0, 0.0, NULL, + NULL); CFMessagePortInvalidate(messageServer); CFRelease(messageServer); diff --git a/toolkit/components/remote/nsMacRemoteServer.mm b/toolkit/components/remote/nsMacRemoteServer.mm index 0936d4d2fd76..f7c6ea234a3f 100644 --- a/toolkit/components/remote/nsMacRemoteServer.mm +++ b/toolkit/components/remote/nsMacRemoteServer.mm @@ -22,20 +22,22 @@ #include "nsXPCOM.h" #include "RemoteUtils.h" -CFDataRef messageServerCallback(CFMessagePortRef aLocal, int32_t aMsgid, CFDataRef aData, - void* aInfo) { +CFDataRef messageServerCallback(CFMessagePortRef aLocal, int32_t aMsgid, + CFDataRef aData, void* aInfo) { // One of the clients submitted a structure. static_cast(aInfo)->HandleCommandLine(aData); return NULL; } -// aData contains serialized Dictionary, which in turn contains command line arguments +// aData contains serialized Dictionary, which in turn contains command line +// arguments void nsMacRemoteServer::HandleCommandLine(CFDataRef aData) { mozilla::MacAutoreleasePool pool; if (aData) { - NSDictionary* dict = [NSKeyedUnarchiver unarchiveObjectWithData:(NSData*)aData]; + NSDictionary* dict = + [NSKeyedUnarchiver unarchiveObjectWithData:(NSData*)aData]; if (dict && [dict isKindOfClass:[NSDictionary class]]) { NSArray* args = dict[@"args"]; if (!args) { @@ -54,7 +56,8 @@ void nsMacRemoteServer::HandleCommandLine(CFDataRef aData) { argv[i] = arg; } - nsresult rv = cmdLine->Init(argc, argv, nullptr, nsICommandLine::STATE_REMOTE_AUTO); + nsresult rv = + cmdLine->Init(argc, argv, nullptr, nsICommandLine::STATE_REMOTE_AUTO); // Cleaning up C array. delete[] argv; @@ -75,21 +78,22 @@ void nsMacRemoteServer::HandleCommandLine(CFDataRef aData) { } } -nsresult nsMacRemoteServer::Startup(const char* aAppName, const char* aProfileName) { +nsresult nsMacRemoteServer::Startup(const char* aAppName, + const char* aProfileName) { // This is the first instance ever. // Let's register a notification listener here, - // In case future instances would want to notify us about command line arguments - // passed to them. Note, that if mozilla process is restarting, we still need to - // register for notifications. + // In case future instances would want to notify us about command line + // arguments passed to them. Note, that if mozilla process is restarting, we + // still need to register for notifications. mozilla::MacAutoreleasePool pool; nsString className; BuildClassName(aAppName, aProfileName, className); - NSString* serverNameString = - [NSString stringWithCharacters:reinterpret_cast(className.get()) - length:className.Length()]; + NSString* serverNameString = [NSString + stringWithCharacters:reinterpret_cast(className.get()) + length:className.Length()]; CFMessagePortContext context; context.copyDescription = NULL; @@ -97,8 +101,9 @@ nsresult nsMacRemoteServer::Startup(const char* aAppName, const char* aProfileNa context.release = NULL; context.retain = NULL; context.version = NULL; - mMessageServer = CFMessagePortCreateLocal(NULL, (CFStringRef)serverNameString, - messageServerCallback, &context, NULL); + mMessageServer = + CFMessagePortCreateLocal(NULL, (CFStringRef)serverNameString, + messageServerCallback, &context, NULL); if (!mMessageServer) { return NS_ERROR_FAILURE; } diff --git a/toolkit/crashreporter/client/crashreporter_osx.mm b/toolkit/crashreporter/client/crashreporter_osx.mm index 38b3349a0466..b6d5d8ac6fce 100644 --- a/toolkit/crashreporter/client/crashreporter_osx.mm +++ b/toolkit/crashreporter/client/crashreporter_osx.mm @@ -61,7 +61,8 @@ static bool RestartApplication() { // Set spawn attributes. size_t attr_count = sizeof(pref_cpu_types) / sizeof(pref_cpu_types[0]); size_t attr_ocount = 0; - if (posix_spawnattr_setbinpref_np(&spawnattr, attr_count, pref_cpu_types, &attr_ocount) != 0 || + if (posix_spawnattr_setbinpref_np(&spawnattr, attr_count, pref_cpu_types, + &attr_ocount) != 0 || attr_ocount != attr_count) { posix_spawnattr_destroy(&spawnattr); return false; @@ -89,7 +90,8 @@ static bool RestartApplication() { gUI = self; [mWindow center]; - [mWindow setTitle:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"]]; + [mWindow setTitle:[[NSBundle mainBundle] + objectForInfoDictionaryKey:@"CFBundleName"]]; [NSApp activateIgnoringOtherApps:YES]; } @@ -189,7 +191,9 @@ static bool RestartApplication() { [self setView:mErrorView animate:NO]; [mErrorHeaderLabel setStringValue:Str(ST_CRASHREPORTERHEADER)]; - [self setStringFitVertically:mErrorLabel string:NSSTR(message) resizeWindow:YES]; + [self setStringFitVertically:mErrorLabel + string:NSSTR(message) + resizeWindow:YES]; [mErrorCloseButton setTitle:Str(ST_OK)]; [mErrorCloseButton setKeyEquivalent:@"\r"]; @@ -199,19 +203,22 @@ static bool RestartApplication() { - (void)showReportInfo { NSDictionary* boldAttr = @{ - NSFontAttributeName : [NSFont boldSystemFontOfSize:[NSFont smallSystemFontSize]], + NSFontAttributeName : + [NSFont boldSystemFontOfSize:[NSFont smallSystemFontSize]], NSForegroundColorAttributeName : NSColor.textColor, }; NSDictionary* normalAttr = @{ - NSFontAttributeName : [NSFont systemFontOfSize:[NSFont smallSystemFontSize]], + NSFontAttributeName : + [NSFont systemFontOfSize:[NSFont smallSystemFontSize]], NSForegroundColorAttributeName : NSColor.textColor, }; [mViewReportTextView setString:@""]; - for (Json::ValueConstIterator iter = gQueryParameters.begin(); iter != gQueryParameters.end(); - ++iter) { - NSAttributedString* key = [[NSAttributedString alloc] initWithString:NSSTR(iter.name() + ": ") - attributes:boldAttr]; + for (Json::ValueConstIterator iter = gQueryParameters.begin(); + iter != gQueryParameters.end(); ++iter) { + NSAttributedString* key = + [[NSAttributedString alloc] initWithString:NSSTR(iter.name() + ": ") + attributes:boldAttr]; string str; if (iter->isString()) { str = iter->asString(); @@ -220,24 +227,27 @@ static bool RestartApplication() { builder["indentation"] = ""; str = writeString(builder, *iter); } - NSAttributedString* value = [[NSAttributedString alloc] initWithString:NSSTR(str + "\n") - attributes:normalAttr]; + NSAttributedString* value = + [[NSAttributedString alloc] initWithString:NSSTR(str + "\n") + attributes:normalAttr]; [[mViewReportTextView textStorage] appendAttributedString:key]; [[mViewReportTextView textStorage] appendAttributedString:value]; [key release]; [value release]; } - NSAttributedString* extra = - [[NSAttributedString alloc] initWithString:NSSTR("\n" + gStrings[ST_EXTRAREPORTINFO]) - attributes:normalAttr]; + NSAttributedString* extra = [[NSAttributedString alloc] + initWithString:NSSTR("\n" + gStrings[ST_EXTRAREPORTINFO]) + attributes:normalAttr]; [[mViewReportTextView textStorage] appendAttributedString:extra]; [extra release]; } - (void)maybeSubmitReport { if ([mSubmitReportButton state] == NSOnState) { - [self setStringFitVertically:mProgressText string:Str(ST_REPORTDURINGSUBMIT) resizeWindow:YES]; + [self setStringFitVertically:mProgressText + string:Str(ST_REPORTDURINGSUBMIT) + resizeWindow:YES]; // disable all the controls [self enableControls:NO]; [mSubmitReportButton setEnabled:NO]; @@ -258,7 +268,8 @@ static bool RestartApplication() { - (IBAction)submitReportClicked:(id)sender { [self updateSubmit]; NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults]; - [userDefaults setBool:([mSubmitReportButton state] == NSOnState) forKey:@"submitReport"]; + [userDefaults setBool:([mSubmitReportButton state] == NSOnState) + forKey:@"submitReport"]; [userDefaults synchronize]; } @@ -288,14 +299,16 @@ static bool RestartApplication() { - (IBAction)includeURLClicked:(id)sender { [self updateURL]; NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults]; - [userDefaults setBool:([mIncludeURLButton state] == NSOnState) forKey:@"IncludeURL"]; + [userDefaults setBool:([mIncludeURLButton state] == NSOnState) + forKey:@"IncludeURL"]; [userDefaults synchronize]; } - (void)textDidChange:(NSNotification*)aNotification { // update comment parameter if ([[[mCommentText textStorage] mutableString] length] > 0) - gQueryParameters["Comments"] = [[[mCommentText textStorage] mutableString] UTF8String]; + gQueryParameters["Comments"] = + [[[mCommentText textStorage] mutableString] UTF8String]; else gQueryParameters.removeMember("Comments"); } @@ -308,7 +321,8 @@ static bool RestartApplication() { if (([[aTextView string] lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + [replacementString lengthOfBytesUsingEncoding:NSUTF8StringEncoding] - [[[aTextView string] substringWithRange:affectedCharRange] - lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) > MAX_COMMENT_LENGTH) { + lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) > + MAX_COMMENT_LENGTH) { return NO; } return YES; @@ -331,8 +345,8 @@ static bool RestartApplication() { if (gRestartArgs.size() == 0) { [mRestartButton removeFromSuperview]; if (!gRTLlayout) { - closeFrame.origin.x = - restartFrame.origin.x + (restartFrame.size.width - closeFrame.size.width); + closeFrame.origin.x = restartFrame.origin.x + + (restartFrame.size.width - closeFrame.size.width); } else { closeFrame.origin.x = restartFrame.origin.x; } @@ -357,7 +371,8 @@ static bool RestartApplication() { // possibly resize window if both buttons no longer fit // leave 20 px from either side of the window, and 12 px // between the buttons - float neededWidth = closeFrame.size.width + restartFrame.size.width + 2 * 20 + 12; + float neededWidth = + closeFrame.size.width + restartFrame.size.width + 2 * 20 + 12; if (neededWidth > windowFrame.size.width) { windowFrame.size.width = neededWidth; @@ -379,7 +394,8 @@ static bool RestartApplication() { [checkbox setFrame:frame]; } // keep existing spacing on left side, + 20 px spare on right - float neededWidth = frame.origin.x + checkbox.intrinsicContentSize.width + 20; + float neededWidth = + frame.origin.x + checkbox.intrinsicContentSize.width + 20; if (neededWidth > windowFrame.size.width) { windowFrame.size.width = neededWidth; [mWindow setFrame:windowFrame display:true animate:NO]; @@ -395,8 +411,9 @@ static bool RestartApplication() { // now pin all the controls (except quit/submit) in place, // if we lengthen the window after this, it's just to lengthen // the progress text, so nothing above that text should move. - NSView* views[] = {mSubmitReportButton, mViewReportButton, mCommentScrollView, - mIncludeURLButton, mProgressIndicator, mProgressText}; + NSView* views[] = {mSubmitReportButton, mViewReportButton, + mCommentScrollView, mIncludeURLButton, + mProgressIndicator, mProgressText}; for (auto view : views) { [view setAutoresizingMask:NSViewMinYMargin]; } @@ -454,7 +471,9 @@ static bool RestartApplication() { - (void)updateSubmit { if ([mSubmitReportButton state] == NSOnState) { - [self setStringFitVertically:mProgressText string:Str(ST_REPORTPRESUBMIT) resizeWindow:YES]; + [self setStringFitVertically:mProgressText + string:Str(ST_REPORTPRESUBMIT) + resizeWindow:YES]; [mProgressText setHidden:NO]; // enable all the controls [self enableControls:YES]; @@ -490,18 +509,24 @@ static bool RestartApplication() { [NSApp terminate:self]; } - [self setStringFitVertically:mProgressText string:Str(ST_SUBMITFAILED) resizeWindow:YES]; + [self setStringFitVertically:mProgressText + string:Str(ST_SUBMITFAILED) + resizeWindow:YES]; // quit after 5 seconds - [self performSelector:@selector(closeMeDown:) withObject:nil afterDelay:5.0]; + [self performSelector:@selector(closeMeDown:) + withObject:nil + afterDelay:5.0]; } - [NSThread detachNewThreadSelector:@selector(uploadThread:) toTarget:self withObject:mPost]; + [NSThread detachNewThreadSelector:@selector(uploadThread:) + toTarget:self + withObject:mPost]; } - (bool)setupPost { - NSURL* url = - [NSURL URLWithString:[NSSTR(gSendURL) - stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + NSURL* url = [NSURL + URLWithString:[NSSTR(gSendURL) stringByAddingPercentEscapesUsingEncoding: + NSUTF8StringEncoding]]; if (!url) return false; mPost = [[HTTPMultipartUpload alloc] initWithURL:url]; @@ -514,7 +539,8 @@ static bool RestartApplication() { Json::StreamWriterBuilder builder; builder["indentation"] = ""; string output = writeString(builder, gQueryParameters).append("\r\n"); - NSMutableString* parameters = [[NSMutableString alloc] initWithUTF8String:output.c_str()]; + NSMutableString* parameters = + [[NSMutableString alloc] initWithUTF8String:output.c_str()]; [mPost setParameters:parameters]; [parameters release]; @@ -535,7 +561,8 @@ static bool RestartApplication() { // if data is nil, we probably logged an error in uploadThread if (data != nil && response != nil) { ostringstream message; - message << "Crash report submission failed: server returned status " << [response statusCode]; + message << "Crash report submission failed: server returned status " + << [response statusCode]; LogMessage(message.str()); } } else { @@ -563,9 +590,13 @@ static bool RestartApplication() { [mProgressIndicator stopAnimation:self]; if (success) { - [self setStringFitVertically:mProgressText string:Str(ST_REPORTSUBMITSUCCESS) resizeWindow:YES]; + [self setStringFitVertically:mProgressText + string:Str(ST_REPORTSUBMITSUCCESS) + resizeWindow:YES]; } else { - [self setStringFitVertically:mProgressText string:Str(ST_SUBMITFAILED) resizeWindow:YES]; + [self setStringFitVertically:mProgressText + string:Str(ST_SUBMITFAILED) + resizeWindow:YES]; } // quit after 5 seconds [self performSelector:@selector(closeMeDown:) withObject:nil afterDelay:5.0]; @@ -582,13 +613,16 @@ static bool RestartApplication() { LogMessage("Crash report submission failed: " + message); } - [self performSelectorOnMainThread:@selector(uploadComplete:) withObject:data waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(uploadComplete:) + withObject:data + waitUntilDone:YES]; [autoreleasepool release]; } // to get auto-quit when we close the window -- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)theApplication { +- (BOOL)applicationShouldTerminateAfterLastWindowClosed: + (NSApplication*)theApplication { return YES; } @@ -621,10 +655,12 @@ static bool RestartApplication() { - (void)setPlaceholder:(NSString*)placeholder { NSColor* txtColor = [NSColor disabledControlTextColor]; - NSDictionary* txtDict = - [NSDictionary dictionaryWithObjectsAndKeys:txtColor, NSForegroundColorAttributeName, nil]; - mPlaceHolderString = [[NSMutableAttributedString alloc] initWithString:placeholder - attributes:txtDict]; + NSDictionary* txtDict = [NSDictionary + dictionaryWithObjectsAndKeys:txtColor, NSForegroundColorAttributeName, + nil]; + mPlaceHolderString = + [[NSMutableAttributedString alloc] initWithString:placeholder + attributes:txtDict]; if (gRTLlayout) [mPlaceHolderString setAlignment:NSTextAlignmentRight range:NSMakeRange(0, [placeholder length])]; @@ -649,9 +685,11 @@ static bool RestartApplication() { txtColor = [NSColor textColor]; else txtColor = [NSColor disabledControlTextColor]; - NSDictionary* txtDict = - [NSDictionary dictionaryWithObjectsAndKeys:txtColor, NSForegroundColorAttributeName, nil]; - colorString = [[NSAttributedString alloc] initWithString:[self string] attributes:txtDict]; + NSDictionary* txtDict = [NSDictionary + dictionaryWithObjectsAndKeys:txtColor, NSForegroundColorAttributeName, + nil]; + colorString = [[NSAttributedString alloc] initWithString:[self string] + attributes:txtDict]; [[self textStorage] setAttributedString:colorString]; [self setInsertionPointColor:txtColor]; [colorString release]; @@ -671,14 +709,16 @@ bool UIInit() { gMainPool = [[NSAutoreleasePool alloc] init]; [NSApplication sharedApplication]; - if (gStrings.find("isRTL") != gStrings.end() && gStrings["isRTL"] == "yes") gRTLlayout = true; + if (gStrings.find("isRTL") != gStrings.end() && gStrings["isRTL"] == "yes") + gRTLlayout = true; if (gAutoSubmit) { gUI = [[CrashReporterUI alloc] init]; } else { - [[NSBundle mainBundle] loadNibNamed:(gRTLlayout ? @"MainMenuRTL" : @"MainMenu") - owner:NSApp - topLevelObjects:nil]; + [[NSBundle mainBundle] + loadNibNamed:(gRTLlayout ? @"MainMenuRTL" : @"MainMenu") + owner:NSApp + topLevelObjects:nil]; } return true; @@ -724,9 +764,10 @@ bool UIGetIniPath(string& path) { return true; } -bool UIGetSettingsPath(const string& vendor, const string& product, string& settingsPath) { - NSArray* paths = - NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); +bool UIGetSettingsPath(const string& vendor, const string& product, + string& settingsPath) { + NSArray* paths = NSSearchPathForDirectoriesInDomains( + NSApplicationSupportDirectory, NSUserDomainMask, YES); NSString* destPath = [paths firstObject]; // Note that MacOS ignores the vendor when creating the profile hierarchy - @@ -751,10 +792,12 @@ bool UIMoveFile(const string& file, const string& newfile) { if (errno != EXDEV) return false; NSFileManager* fileManager = [NSFileManager defaultManager]; - NSString* source = [fileManager stringWithFileSystemRepresentation:file.c_str() - length:file.length()]; - NSString* dest = [fileManager stringWithFileSystemRepresentation:newfile.c_str() - length:newfile.length()]; + NSString* source = + [fileManager stringWithFileSystemRepresentation:file.c_str() + length:file.length()]; + NSString* dest = + [fileManager stringWithFileSystemRepresentation:newfile.c_str() + length:newfile.length()]; if (!source || !dest) return false; [fileManager moveItemAtPath:source toPath:dest error:NULL]; diff --git a/toolkit/mozapps/update/updater/launchchild_osx.mm b/toolkit/mozapps/update/updater/launchchild_osx.mm index 87ac9ba5f281..917f282d9f57 100644 --- a/toolkit/mozapps/update/updater/launchchild_osx.mm +++ b/toolkit/mozapps/update/updater/launchchild_osx.mm @@ -55,7 +55,8 @@ bool IsBinaryArmExecutable(const char* executablePath) { bool isArmExecutable = false; CFURLRef url = ::CFURLCreateFromFileSystemRepresentation( - kCFAllocatorDefault, (const UInt8*)executablePath, strlen(executablePath), false); + kCFAllocatorDefault, (const UInt8*)executablePath, strlen(executablePath), + false); if (!url) { return false; } @@ -68,7 +69,8 @@ bool IsBinaryArmExecutable(const char* executablePath) { CFIndex archCount = ::CFArrayGetCount(archs); for (CFIndex i = 0; i < archCount; i++) { - CFNumberRef currentArch = static_cast(::CFArrayGetValueAtIndex(archs, i)); + CFNumberRef currentArch = + static_cast(::CFArrayGetValueAtIndex(archs, i)); int currentArchInt = 0; if (!::CFNumberGetValue(currentArch, kCFNumberIntType, ¤tArchInt)) { continue; @@ -161,7 +163,8 @@ void LaunchMacPostProcess(const char* aAppBundle) { // Launch helper to perform post processing for the update; this is the Mac // analogue of LaunchWinPostProcess (PostUpdateWin). NSString* iniPath = [NSString stringWithUTF8String:aAppBundle]; - iniPath = [iniPath stringByAppendingPathComponent:@"Contents/Resources/updater.ini"]; + iniPath = [iniPath + stringByAppendingPathComponent:@"Contents/Resources/updater.ini"]; NSFileManager* fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:iniPath]) { @@ -171,8 +174,8 @@ void LaunchMacPostProcess(const char* aAppBundle) { int readResult; mozilla::UniquePtr values[2]; - readResult = - ReadStrings([iniPath UTF8String], "ExeRelPath\0ExeArg\0", 2, values, "PostUpdateMac"); + readResult = ReadStrings([iniPath UTF8String], "ExeRelPath\0ExeArg\0", 2, + values, "PostUpdateMac"); if (readResult) { return; } @@ -194,7 +197,8 @@ void LaunchMacPostProcess(const char* aAppBundle) { exeFullPath = [exeFullPath stringByAppendingPathComponent:exeRelPath]; mozilla::UniquePtr optVal; - readResult = ReadStrings([iniPath UTF8String], "ExeAsync\0", 1, &optVal, "PostUpdateMac"); + readResult = ReadStrings([iniPath UTF8String], "ExeAsync\0", 1, &optVal, + "PostUpdateMac"); NSTask* task = [[NSTask alloc] init]; [task setLaunchPath:exeFullPath]; @@ -223,8 +227,10 @@ id ConnectToUpdateServer() { updateServer = (id)[NSConnection rootProxyForConnectionWithRegisteredName:@"org.mozilla.updater.server" host:nil - usingNameServer:[NSSocketPortNameServer sharedInstance]]; - if (!updateServer || ![updateServer respondsToSelector:@selector(abort)] || + usingNameServer:[NSSocketPortNameServer + sharedInstance]]; + if (!updateServer || + ![updateServer respondsToSelector:@selector(abort)] || ![updateServer respondsToSelector:@selector(getArguments)] || ![updateServer respondsToSelector:@selector(shutdown)]) { NSLog(@"Server doesn't exist or doesn't provide correct selectors."); @@ -262,9 +268,13 @@ void CleanupElevatedMacUpdate(bool aFailureOccurred) { } NSFileManager* manager = [NSFileManager defaultManager]; - [manager removeItemAtPath:@"/Library/PrivilegedHelperTools/org.mozilla.updater" error:nil]; - [manager removeItemAtPath:@"/Library/LaunchDaemons/org.mozilla.updater.plist" error:nil]; - const char* launchctlArgs[] = {"/bin/launchctl", "remove", "org.mozilla.updater"}; + [manager + removeItemAtPath:@"/Library/PrivilegedHelperTools/org.mozilla.updater" + error:nil]; + [manager removeItemAtPath:@"/Library/LaunchDaemons/org.mozilla.updater.plist" + error:nil]; + const char* launchctlArgs[] = {"/bin/launchctl", "remove", + "org.mozilla.updater"}; // The following call will terminate the current process due to the "remove" // argument in launchctlArgs. LaunchChild(3, launchctlArgs); @@ -282,13 +292,15 @@ bool ObtainUpdaterArguments(int* argc, char*** argv) { } @try { - NSArray* updaterArguments = [updateServer performSelector:@selector(getArguments)]; + NSArray* updaterArguments = + [updateServer performSelector:@selector(getArguments)]; *argc = [updaterArguments count]; char** tempArgv = (char**)malloc(sizeof(char*) * (*argc)); for (int i = 0; i < *argc; i++) { int argLen = [[updaterArguments objectAtIndex:i] length] + 1; tempArgv[i] = (char*)malloc(argLen); - strncpy(tempArgv[i], [[updaterArguments objectAtIndex:i] UTF8String], argLen); + strncpy(tempArgv[i], [[updaterArguments objectAtIndex:i] UTF8String], + argLen); } *argv = tempArgv; } @catch (NSException* e) { @@ -334,7 +346,8 @@ bool ObtainUpdaterArguments(int* argc, char*** argv) { - (BOOL)runServer { NSPort* serverPort = [NSSocketPort port]; - NSConnection* server = [NSConnection connectionWithReceivePort:serverPort sendPort:serverPort]; + NSConnection* server = [NSConnection connectionWithReceivePort:serverPort + sendPort:serverPort]; [server setRootObject:self]; if ([server registerName:@"org.mozilla.updater.server" withNameServer:[NSSocketPortNameServer sharedInstance]] == NO) { @@ -343,8 +356,9 @@ bool ObtainUpdaterArguments(int* argc, char*** argv) { return NO; } - while ([self shouldKeepRunning] && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode - beforeDate:[NSDate distantFuture]]) + while ([self shouldKeepRunning] && + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode + beforeDate:[NSDate distantFuture]]) ; return ![self wasAborted]; } @@ -394,9 +408,11 @@ bool IsOwnedByGroupAdmin(const char* aAppBundle) { NSString* appDir = [NSString stringWithUTF8String:aAppBundle]; NSFileManager* fileManager = [NSFileManager defaultManager]; - NSDictionary* attributes = [fileManager attributesOfItemAtPath:appDir error:nil]; + NSDictionary* attributes = [fileManager attributesOfItemAtPath:appDir + error:nil]; bool isOwnedByAdmin = false; - if (attributes && [[attributes valueForKey:NSFileGroupOwnerAccountID] intValue] == 80) { + if (attributes && + [[attributes valueForKey:NSFileGroupOwnerAccountID] intValue] == 80) { isOwnedByAdmin = true; } return isOwnedByAdmin; @@ -425,13 +441,14 @@ void SetGroupOwnershipAndPermissions(const char* aAppBundle) { return; } - NSArray* permKeys = - [NSArray arrayWithObjects:NSFileGroupOwnerAccountID, NSFilePosixPermissions, nil]; + NSArray* permKeys = [NSArray + arrayWithObjects:NSFileGroupOwnerAccountID, NSFilePosixPermissions, nil]; // For all descendants of Firefox.app, set group ownership to 80 ("admin") and // ensure write permission for the group. for (NSString* currPath in paths) { NSString* child = [appDir stringByAppendingPathComponent:currPath]; - NSDictionary* oldAttributes = [fileManager attributesOfItemAtPath:child error:&error]; + NSDictionary* oldAttributes = [fileManager attributesOfItemAtPath:child + error:&error]; if (error) { return; } @@ -440,12 +457,20 @@ void SetGroupOwnershipAndPermissions(const char* aAppBundle) { if ([oldAttributes fileType] == NSFileTypeSymbolicLink) { continue; } - NSNumber* oldPerms = (NSNumber*)[oldAttributes valueForKey:NSFilePosixPermissions]; + NSNumber* oldPerms = + (NSNumber*)[oldAttributes valueForKey:NSFilePosixPermissions]; NSArray* permObjects = [NSArray arrayWithObjects:[NSNumber numberWithUnsignedLong:80], - [NSNumber numberWithUnsignedLong:[oldPerms shortValue] | 020], nil]; - NSDictionary* attributes = [NSDictionary dictionaryWithObjects:permObjects forKeys:permKeys]; - if (![fileManager setAttributes:attributes ofItemAtPath:child error:&error] || error) { + [NSNumber + numberWithUnsignedLong:[oldPerms shortValue] | + 020], + nil]; + NSDictionary* attributes = [NSDictionary dictionaryWithObjects:permObjects + forKeys:permKeys]; + if (![fileManager setAttributes:attributes + ofItemAtPath:child + error:&error] || + error) { return; } } @@ -483,7 +508,9 @@ bool PerformInstallationFromDMG(int argc, char** argv) { } NSString* bundlePath = [NSString stringWithUTF8String:argv[2]]; NSString* destPath = [NSString stringWithUTF8String:argv[3]]; - if ([[NSFileManager defaultManager] copyItemAtPath:bundlePath toPath:destPath error:nil]) { + if ([[NSFileManager defaultManager] copyItemAtPath:bundlePath + toPath:destPath + error:nil]) { RegisterAppWithLaunchServices(destPath); StripQuarantineBit(destPath); return true; diff --git a/toolkit/mozapps/update/updater/progressui_osx.mm b/toolkit/mozapps/update/updater/progressui_osx.mm index b6e01ea71efb..4a9f8ef3b1b3 100644 --- a/toolkit/mozapps/update/updater/progressui_osx.mm +++ b/toolkit/mozapps/update/updater/progressui_osx.mm @@ -32,12 +32,14 @@ static const char* sUpdatePath; NSWindow* w = [progressBar window]; [w setTitle:[NSString stringWithUTF8String:sLabels.title.get()]]; - [progressTextField setStringValue:[NSString stringWithUTF8String:sLabels.info.get()]]; + [progressTextField + setStringValue:[NSString stringWithUTF8String:sLabels.info.get()]]; NSRect origTextFrame = [progressTextField frame]; [progressTextField sizeToFit]; - int widthAdjust = progressTextField.frame.size.width - origTextFrame.size.width; + int widthAdjust = + progressTextField.frame.size.width - origTextFrame.size.width; if (widthAdjust > 0) { NSRect f; @@ -118,7 +120,9 @@ int ShowProgressUI(bool indeterminate) { sIndeterminate = indeterminate; [NSApplication sharedApplication]; - [[NSBundle mainBundle] loadNibNamed:@"MainMenu" owner:NSApp topLevelObjects:nil]; + [[NSBundle mainBundle] loadNibNamed:@"MainMenu" + owner:NSApp + topLevelObjects:nil]; [NSApp run]; return 0; diff --git a/toolkit/system/osxproxy/nsOSXSystemProxySettings.mm b/toolkit/system/osxproxy/nsOSXSystemProxySettings.mm index 210b3bb247ff..b1ad41ccc109 100644 --- a/toolkit/system/osxproxy/nsOSXSystemProxySettings.mm +++ b/toolkit/system/osxproxy/nsOSXSystemProxySettings.mm @@ -34,8 +34,8 @@ class nsOSXSystemProxySettings : public nsISystemProxySettings { nsresult GetAutoconfigURL(nsAutoCString& aResult) const; // Find the SystemConfiguration proxy & port for a given URI - nsresult FindSCProxyPort(const nsACString& aScheme, nsACString& aResultHost, int32_t& aResultPort, - bool& aResultSocksProxy); + nsresult FindSCProxyPort(const nsACString& aScheme, nsACString& aResultHost, + int32_t& aResultPort, bool& aResultSocksProxy); // is host:port on the proxy exception list? bool IsInExceptionList(const nsACString& aHost) const; @@ -69,22 +69,26 @@ nsOSXSystemProxySettings::GetMainThreadOnly(bool* aMainThreadOnly) { } // Mapping of URI schemes to SystemConfiguration keys -const nsOSXSystemProxySettings::SchemeMapping nsOSXSystemProxySettings::gSchemeMappingList[] = { - {"http", kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPProxy, kSCPropNetProxiesHTTPPort, - false}, - {"https", kSCPropNetProxiesHTTPSEnable, kSCPropNetProxiesHTTPSProxy, kSCPropNetProxiesHTTPSPort, - false}, - {"ftp", kSCPropNetProxiesFTPEnable, kSCPropNetProxiesFTPProxy, kSCPropNetProxiesFTPPort, false}, - {"socks", kSCPropNetProxiesSOCKSEnable, kSCPropNetProxiesSOCKSProxy, kSCPropNetProxiesSOCKSPort, - true}, - {NULL, NULL, NULL, NULL, false}, +const nsOSXSystemProxySettings::SchemeMapping + nsOSXSystemProxySettings::gSchemeMappingList[] = { + {"http", kSCPropNetProxiesHTTPEnable, kSCPropNetProxiesHTTPProxy, + kSCPropNetProxiesHTTPPort, false}, + {"https", kSCPropNetProxiesHTTPSEnable, kSCPropNetProxiesHTTPSProxy, + kSCPropNetProxiesHTTPSPort, false}, + {"ftp", kSCPropNetProxiesFTPEnable, kSCPropNetProxiesFTPProxy, + kSCPropNetProxiesFTPPort, false}, + {"socks", kSCPropNetProxiesSOCKSEnable, kSCPropNetProxiesSOCKSProxy, + kSCPropNetProxiesSOCKSPort, true}, + {NULL, NULL, NULL, NULL, false}, }; -static void ProxyHasChangedWrapper(SCDynamicStoreRef aStore, CFArrayRef aChangedKeys, void* aInfo) { +static void ProxyHasChangedWrapper(SCDynamicStoreRef aStore, + CFArrayRef aChangedKeys, void* aInfo) { static_cast(aInfo)->ProxyHasChanged(); } -nsOSXSystemProxySettings::nsOSXSystemProxySettings() : mSystemDynamicStore(NULL), mProxyDict(NULL) { +nsOSXSystemProxySettings::nsOSXSystemProxySettings() + : mSystemDynamicStore(NULL), mProxyDict(NULL) { mContext = (SCDynamicStoreContext){0, this, NULL, NULL, NULL}; } @@ -94,15 +98,16 @@ nsresult nsOSXSystemProxySettings::Init() { // Register for notification of proxy setting changes // See: // http://developer.apple.com/documentation/Networking/Conceptual/CFNetwork/CFStreamTasks/chapter_4_section_5.html - mSystemDynamicStore = - SCDynamicStoreCreate(NULL, CFSTR("Mozilla"), ProxyHasChangedWrapper, &mContext); + mSystemDynamicStore = SCDynamicStoreCreate(NULL, CFSTR("Mozilla"), + ProxyHasChangedWrapper, &mContext); if (!mSystemDynamicStore) return NS_ERROR_FAILURE; // Set up the store to monitor any changes to the proxies CFStringRef proxiesKey = SCDynamicStoreKeyCreateProxies(NULL); if (!proxiesKey) return NS_ERROR_FAILURE; - CFArrayRef keyArray = CFArrayCreate(NULL, (const void**)(&proxiesKey), 1, &kCFTypeArrayCallBacks); + CFArrayRef keyArray = CFArrayCreate(NULL, (const void**)(&proxiesKey), 1, + &kCFTypeArrayCallBacks); CFRelease(proxiesKey); if (!keyArray) return NS_ERROR_FAILURE; @@ -113,7 +118,8 @@ nsresult nsOSXSystemProxySettings::Init() { CFRunLoopSourceRef storeRLSource = SCDynamicStoreCreateRunLoopSource(NULL, mSystemDynamicStore, 0); if (!storeRLSource) return NS_ERROR_FAILURE; - CFRunLoopAddSource(CFRunLoopGetCurrent(), storeRLSource, kCFRunLoopCommonModes); + CFRunLoopAddSource(CFRunLoopGetCurrent(), storeRLSource, + kCFRunLoopCommonModes); CFRelease(storeRLSource); // Load the initial copy of proxy info @@ -135,7 +141,8 @@ nsOSXSystemProxySettings::~nsOSXSystemProxySettings() { if (mSystemDynamicStore) { // Invalidate the dynamic store's run loop source // to get the store out of the run loop - CFRunLoopSourceRef rls = SCDynamicStoreCreateRunLoopSource(NULL, mSystemDynamicStore, 0); + CFRunLoopSourceRef rls = + SCDynamicStoreCreateRunLoopSource(NULL, mSystemDynamicStore, 0); if (rls) { CFRunLoopSourceInvalidate(rls); CFRelease(rls); @@ -158,20 +165,24 @@ void nsOSXSystemProxySettings::ProxyHasChanged() { } nsresult nsOSXSystemProxySettings::FindSCProxyPort(const nsACString& aScheme, - nsACString& aResultHost, int32_t& aResultPort, + nsACString& aResultHost, + int32_t& aResultPort, bool& aResultSocksProxy) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; NS_ENSURE_TRUE(mProxyDict != NULL, NS_ERROR_FAILURE); - for (const SchemeMapping* keys = gSchemeMappingList; keys->mScheme != NULL; ++keys) { + for (const SchemeMapping* keys = gSchemeMappingList; keys->mScheme != NULL; + ++keys) { // Check for matching scheme (when appropriate) - if (strcasecmp(keys->mScheme, PromiseFlatCString(aScheme).get()) && !keys->mIsSocksProxy) + if (strcasecmp(keys->mScheme, PromiseFlatCString(aScheme).get()) && + !keys->mIsSocksProxy) continue; // Check the proxy is enabled NSNumber* enabled = [mProxyDict objectForKey:(NSString*)keys->mEnabled]; - NS_ENSURE_TRUE(enabled == NULL || [enabled isKindOfClass:[NSNumber class]], NS_ERROR_FAILURE); + NS_ENSURE_TRUE(enabled == NULL || [enabled isKindOfClass:[NSNumber class]], + NS_ERROR_FAILURE); if ([enabled intValue] == 0) continue; // Get the proxy host @@ -198,17 +209,21 @@ nsresult nsOSXSystemProxySettings::FindSCProxyPort(const nsACString& aScheme, bool nsOSXSystemProxySettings::IsAutoconfigEnabled() const { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - NSNumber* value = [mProxyDict objectForKey:(NSString*)kSCPropNetProxiesProxyAutoConfigEnable]; - NS_ENSURE_TRUE(value == NULL || [value isKindOfClass:[NSNumber class]], false); + NSNumber* value = [mProxyDict + objectForKey:(NSString*)kSCPropNetProxiesProxyAutoConfigEnable]; + NS_ENSURE_TRUE(value == NULL || [value isKindOfClass:[NSNumber class]], + false); return ([value intValue] != 0); NS_OBJC_END_TRY_BLOCK_RETURN(false); } -nsresult nsOSXSystemProxySettings::GetAutoconfigURL(nsAutoCString& aResult) const { +nsresult nsOSXSystemProxySettings::GetAutoconfigURL( + nsAutoCString& aResult) const { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - NSString* value = [mProxyDict objectForKey:(NSString*)kSCPropNetProxiesProxyAutoConfigURLString]; + NSString* value = [mProxyDict + objectForKey:(NSString*)kSCPropNetProxiesProxyAutoConfigURLString]; if (value != NULL) { NS_ENSURE_TRUE([value isKindOfClass:[NSString class]], NS_ERROR_FAILURE); aResult.Assign([value UTF8String]); @@ -220,20 +235,25 @@ nsresult nsOSXSystemProxySettings::GetAutoconfigURL(nsAutoCString& aResult) cons NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -bool nsOSXSystemProxySettings::IsInExceptionList(const nsACString& aHost) const { +bool nsOSXSystemProxySettings::IsInExceptionList( + const nsACString& aHost) const { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; NS_ENSURE_TRUE(mProxyDict != NULL, false); - NSArray* exceptionList = [mProxyDict objectForKey:(NSString*)kSCPropNetProxiesExceptionsList]; - NS_ENSURE_TRUE(exceptionList == NULL || [exceptionList isKindOfClass:[NSArray class]], false); + NSArray* exceptionList = + [mProxyDict objectForKey:(NSString*)kSCPropNetProxiesExceptionsList]; + NS_ENSURE_TRUE( + exceptionList == NULL || [exceptionList isKindOfClass:[NSArray class]], + false); NSEnumerator* exceptionEnumerator = [exceptionList objectEnumerator]; NSString* currentValue = NULL; while ((currentValue = [exceptionEnumerator nextObject])) { NS_ENSURE_TRUE([currentValue isKindOfClass:[NSString class]], false); nsAutoCString overrideStr([currentValue UTF8String]); - if (mozilla::toolkit::system::IsHostProxyEntry(aHost, overrideStr)) return true; + if (mozilla::toolkit::system::IsHostProxyEntry(aHost, overrideStr)) + return true; } NS_OBJC_END_TRY_BLOCK_RETURN(false); @@ -257,7 +277,8 @@ nsresult nsOSXSystemProxySettings::GetPACURI(nsACString& aResult) { nsresult nsOSXSystemProxySettings::GetProxyForURI(const nsACString& aSpec, const nsACString& aScheme, - const nsACString& aHost, const int32_t aPort, + const nsACString& aHost, + const int32_t aPort, nsACString& aResult) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; @@ -283,7 +304,8 @@ using namespace mozilla::net; class OSXSystemProxySettingsAsync final : public nsOSXSystemProxySettings { public: - NS_INLINE_DECL_REFCOUNTING_INHERITED(OSXSystemProxySettingsAsync, nsOSXSystemProxySettings) + NS_INLINE_DECL_REFCOUNTING_INHERITED(OSXSystemProxySettingsAsync, + nsOSXSystemProxySettings) NS_DECL_NSISYSTEMPROXYSETTINGS OSXSystemProxySettingsAsync(); @@ -314,7 +336,8 @@ void OSXSystemProxySettingsAsync::OnProxyConfigChangedInternal() { } // proxies (for now: PROXY and SOCKS) - for (const SchemeMapping* keys = gSchemeMappingList; keys->mScheme != NULL; ++keys) { + for (const SchemeMapping* keys = gSchemeMappingList; keys->mScheme != NULL; + ++keys) { // Check the proxy is enabled NSNumber* enabled = [mProxyDict objectForKey:(NSString*)keys->mEnabled]; if (!(enabled == NULL || [enabled isKindOfClass:[NSNumber class]])) { @@ -342,17 +365,20 @@ void OSXSystemProxySettingsAsync::OnProxyConfigChangedInternal() { } int32_t resultPort = [port intValue]; - ProxyServer server(ProxyConfig::ToProxyType(keys->mScheme), resultHost, resultPort); + ProxyServer server(ProxyConfig::ToProxyType(keys->mScheme), resultHost, + resultPort); config.Rules().mProxyServers[server.Type()] = std::move(server); } // exceptions - NSArray* exceptionList = [mProxyDict objectForKey:(NSString*)kSCPropNetProxiesExceptionsList]; + NSArray* exceptionList = + [mProxyDict objectForKey:(NSString*)kSCPropNetProxiesExceptionsList]; if (exceptionList != NULL && [exceptionList isKindOfClass:[NSArray class]]) { NSEnumerator* exceptionEnumerator = [exceptionList objectEnumerator]; NSString* currentValue = NULL; while ((currentValue = [exceptionEnumerator nextObject])) { - if (currentValue != NULL && [currentValue isKindOfClass:[NSString class]]) { + if (currentValue != NULL && + [currentValue isKindOfClass:[NSString class]]) { nsCString overrideStr([currentValue UTF8String]); config.ByPassRules().mExceptions.AppendElement(std::move(overrideStr)); } @@ -374,8 +400,10 @@ OSXSystemProxySettingsAsync::GetPACURI(nsACString& aResult) { } NS_IMETHODIMP -OSXSystemProxySettingsAsync::GetProxyForURI(const nsACString& aSpec, const nsACString& aScheme, - const nsACString& aHost, const int32_t aPort, +OSXSystemProxySettingsAsync::GetProxyForURI(const nsACString& aSpec, + const nsACString& aScheme, + const nsACString& aHost, + const int32_t aPort, nsACString& aResult) { for (const auto& bypassRule : mConfig.ByPassRules().mExceptions) { if (mozilla::toolkit::system::IsHostProxyEntry(aHost, bypassRule)) { @@ -389,9 +417,10 @@ OSXSystemProxySettingsAsync::GetProxyForURI(const nsACString& aSpec, const nsACS } NS_IMPL_COMPONENT_FACTORY(nsOSXSystemProxySettings) { - auto settings = mozilla::StaticPrefs::network_proxy_detect_system_proxy_changes() - ? mozilla::MakeRefPtr() - : mozilla::MakeRefPtr(); + auto settings = + mozilla::StaticPrefs::network_proxy_detect_system_proxy_changes() + ? mozilla::MakeRefPtr() + : mozilla::MakeRefPtr(); if (NS_SUCCEEDED(settings->Init())) { return settings.forget().downcast(); } diff --git a/toolkit/xre/MacApplicationDelegate.mm b/toolkit/xre/MacApplicationDelegate.mm index 215798fa2412..804189201a8f 100644 --- a/toolkit/xre/MacApplicationDelegate.mm +++ b/toolkit/xre/MacApplicationDelegate.mm @@ -5,8 +5,9 @@ // NSApplication delegate for Mac OS X Cocoa API. -// As of 10.4 Tiger, the system can send six kinds of Apple Events to an application; -// a well-behaved XUL app should have some kind of handling for all of them. +// As of 10.4 Tiger, the system can send six kinds of Apple Events to an +// application; a well-behaved XUL app should have some kind of handling for all +// of them. // // See // http://developer.apple.com/documentation/Cocoa/Conceptual/ScriptableCocoaApplications/SApps_handle_AEs/chapter_11_section_3.html @@ -92,7 +93,9 @@ void SetupMacApplicationDelegate(bool* gRestartedByOS) { // This call makes it so that application:openFile: doesn't get bogus calls // from Cocoa doing its own parsing of the argument string. And yes, we need // to use a string with a boolean value in it. That's just how it works. - [[NSUserDefaults standardUserDefaults] setObject:@"NO" forKey:@"NSTreatUnknownArgumentsAsOpen"]; + [[NSUserDefaults standardUserDefaults] + setObject:@"NO" + forKey:@"NSTreatUnknownArgumentsAsOpen"]; // Create the delegate. This should be around for the lifetime of the app. id delegate = [[MacApplicationDelegate alloc] init]; @@ -164,9 +167,11 @@ void ProcessPendingGetURLAppleEvents() { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; NSAppleEventManager* aeMgr = [NSAppleEventManager sharedAppleEventManager]; - [aeMgr removeEventHandlerForEventClass:kInternetEventClass andEventID:kAEGetURL]; + [aeMgr removeEventHandlerForEventClass:kInternetEventClass + andEventID:kAEGetURL]; [aeMgr removeEventHandlerForEventClass:'WWW!' andEventID:'OURL']; - [aeMgr removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEOpenDocuments]; + [aeMgr removeEventHandlerForEventClass:kCoreEventClass + andEventID:kAEOpenDocuments]; [super dealloc]; NS_OBJC_END_TRY_IGNORE_BLOCK; @@ -175,7 +180,8 @@ void ProcessPendingGetURLAppleEvents() { // The method that NSApplication calls upon a request to reopen, such as when // the Dock icon is clicked and no windows are open. A "visible" window may be // miniaturized, so we can't skip nsCocoaNativeReOpen() if 'flag' is 'true'. -- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApp hasVisibleWindows:(BOOL)flag { +- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApp + hasVisibleWindows:(BOOL)flag { nsCOMPtr nas = NS_GetNativeAppSupport(); NS_ENSURE_TRUE(nas, NO); @@ -187,9 +193,10 @@ void ProcessPendingGetURLAppleEvents() { return NO; } -// The method that NSApplication calls when documents are requested to be opened. -// It will be called once for each selected document. -- (BOOL)application:(NSApplication*)theApplication openFile:(NSString*)filename { +// The method that NSApplication calls when documents are requested to be +// opened. It will be called once for each selected document. +- (BOOL)application:(NSApplication*)theApplication + openFile:(NSString*)filename { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; NSURL* url = [NSURL fileURLWithPath:filename]; @@ -199,10 +206,12 @@ void ProcessPendingGetURLAppleEvents() { if (!urlString) return NO; // Add the URL to any command line we're currently setting up. - if (CommandLineServiceMac::AddURLToCurrentCommandLine([urlString UTF8String])) return YES; + if (CommandLineServiceMac::AddURLToCurrentCommandLine([urlString UTF8String])) + return YES; nsCOMPtr inFile; - nsresult rv = NS_NewLocalFileWithCFURL((CFURLRef)url, true, getter_AddRefs(inFile)); + nsresult rv = + NS_NewLocalFileWithCFURL((CFURLRef)url, true, getter_AddRefs(inFile)); if (NS_FAILED(rv)) return NO; nsCOMPtr cmdLine(new nsCommandLine()); @@ -212,14 +221,16 @@ void ProcessPendingGetURLAppleEvents() { if (NS_FAILED(rv)) return NO; nsCOMPtr workingDir; - rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir)); + rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, + getter_AddRefs(workingDir)); if (NS_FAILED(rv)) { // Couldn't find a working dir. Uh oh. Good job cmdline::Init can cope. workingDir = nullptr; } const char* argv[3] = {nullptr, "-file", filePath.get()}; - rv = cmdLine->Init(3, argv, workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT); + rv = + cmdLine->Init(3, argv, workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT); if (NS_FAILED(rv)) return NO; if (NS_SUCCEEDED(cmdLine->Run())) return YES; @@ -229,10 +240,11 @@ void ProcessPendingGetURLAppleEvents() { NS_OBJC_END_TRY_BLOCK_RETURN(NO); } -// The method that NSApplication calls when documents are requested to be printed -// from the Finder (under the "File" menu). -// It will be called once for each selected document. -- (BOOL)application:(NSApplication*)theApplication printFile:(NSString*)filename { +// The method that NSApplication calls when documents are requested to be +// printed from the Finder (under the "File" menu). It will be called once for +// each selected document. +- (BOOL)application:(NSApplication*)theApplication + printFile:(NSString*)filename { return NO; } @@ -256,7 +268,8 @@ void ProcessPendingGetURLAppleEvents() { if (NS_FAILED(rv) || !dockMenuInterface) return menu; RefPtr dockMenu = - static_cast(dockMenuInterface.get())->GetNativeMenu(); + static_cast(dockMenuInterface.get()) + ->GetNativeMenu(); // Give the menu the opportunity to update itself before display. dockMenu->MenuWillOpen(); @@ -288,16 +301,21 @@ void ProcessPendingGetURLAppleEvents() { - (void)applicationWillFinishLaunching:(NSNotification*)notification { // We provide our own full screen menu item, so we don't want the OS providing // one as well. - [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSFullScreenMenuItemEverywhere"]; + [[NSUserDefaults standardUserDefaults] + setBool:NO + forKey:@"NSFullScreenMenuItemEverywhere"]; } // If we don't handle applicationShouldTerminate:, a call to [NSApp terminate:] // (from the browser or from the OS) can result in an unclean shutdown. -- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender { - nsCOMPtr obsServ = do_GetService("@mozilla.org/observer-service;1"); +- (NSApplicationTerminateReply)applicationShouldTerminate: + (NSApplication*)sender { + nsCOMPtr obsServ = + do_GetService("@mozilla.org/observer-service;1"); if (!obsServ) return NSTerminateNow; - nsCOMPtr cancelQuit = do_CreateInstance(NS_SUPPORTS_PRBOOL_CONTRACTID); + nsCOMPtr cancelQuit = + do_CreateInstance(NS_SUPPORTS_PRBOOL_CONTRACTID); if (!cancelQuit) return NSTerminateNow; cancelQuit->SetData(false); @@ -307,7 +325,8 @@ void ProcessPendingGetURLAppleEvents() { cancelQuit->GetData(&abortQuit); if (abortQuit) return NSTerminateCancel; - nsCOMPtr appService = do_GetService("@mozilla.org/toolkit/app-startup;1"); + nsCOMPtr appService = + do_GetService("@mozilla.org/toolkit/app-startup;1"); if (appService) { bool userAllowedQuit = true; appService->Quit(nsIAppStartup::eForceQuit, 0, &userAllowedQuit); @@ -325,22 +344,28 @@ void ProcessPendingGetURLAppleEvents() { AutoAutoreleasePool pool; - bool isGetURLEvent = ([event eventClass] == kInternetEventClass && [event eventID] == kAEGetURL); + bool isGetURLEvent = ([event eventClass] == kInternetEventClass && + [event eventID] == kAEGetURL); if (isGetURLEvent) sProcessedGetURLEvent = true; - if (isGetURLEvent || ([event eventClass] == 'WWW!' && [event eventID] == 'OURL')) { - NSString* urlString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; + if (isGetURLEvent || + ([event eventClass] == 'WWW!' && [event eventID] == 'OURL')) { + NSString* urlString = + [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; NSURL* url = [NSURL URLWithString:urlString]; [self openURL:url]; - } else if ([event eventClass] == kCoreEventClass && [event eventID] == kAEOpenDocuments) { - NSAppleEventDescriptor* fileListDescriptor = [event paramDescriptorForKeyword:keyDirectObject]; + } else if ([event eventClass] == kCoreEventClass && + [event eventID] == kAEOpenDocuments) { + NSAppleEventDescriptor* fileListDescriptor = + [event paramDescriptorForKeyword:keyDirectObject]; if (!fileListDescriptor) return; // Descriptor list indexing is one-based... NSInteger numberOfFiles = [fileListDescriptor numberOfItems]; for (NSInteger i = 1; i <= numberOfFiles; i++) { - NSString* urlString = [[fileListDescriptor descriptorAtIndex:i] stringValue]; + NSString* urlString = + [[fileListDescriptor descriptorAtIndex:i] stringValue]; if (!urlString) continue; // We need a path, not a URL @@ -359,12 +384,15 @@ void ProcessPendingGetURLAppleEvents() { - (BOOL)application:(NSApplication*)application continueUserActivity:(NSUserActivity*)userActivity -#if defined(MAC_OS_X_VERSION_10_14) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_14 - restorationHandler:(void (^)(NSArray>*))restorationHandler { +#if defined(MAC_OS_X_VERSION_10_14) && \ + MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_14 + restorationHandler: + (void (^)(NSArray>*))restorationHandler { #else restorationHandler:(void (^)(NSArray*))restorationHandler { #endif - if (![userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) { + if (![userActivity.activityType + isEqualToString:NSUserActivityTypeBrowsingWeb]) { return NO; } @@ -378,7 +406,8 @@ void ProcessPendingGetURLAppleEvents() { } - (BOOL)openURL:(NSURL*)url { - if (!url || !url.scheme || [url.scheme caseInsensitiveCompare:@"chrome"] == NSOrderedSame) { + if (!url || !url.scheme || + [url.scheme caseInsensitiveCompare:@"chrome"] == NSOrderedSame) { return NO; } @@ -390,14 +419,16 @@ void ProcessPendingGetURLAppleEvents() { nsCOMPtr cmdLine(new nsCommandLine()); nsCOMPtr workingDir; - nsresult rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir)); + nsresult rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, + getter_AddRefs(workingDir)); if (NS_FAILED(rv)) { // Couldn't find a working dir. Uh oh. Good job cmdline::Init can cope. workingDir = nullptr; } const char* argv[3] = {nullptr, "-url", urlString}; - rv = cmdLine->Init(3, argv, workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT); + rv = + cmdLine->Init(3, argv, workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT); if (NS_FAILED(rv)) { return NO; } diff --git a/toolkit/xre/MacLaunchHelper.mm b/toolkit/xre/MacLaunchHelper.mm index 555e15d08479..127e7081e1fa 100644 --- a/toolkit/xre/MacLaunchHelper.mm +++ b/toolkit/xre/MacLaunchHelper.mm @@ -26,7 +26,8 @@ void LaunchChildMac(int aArgc, char** aArgv, pid_t* aPid) { for (int i = 1; i < aArgc; i++) { [arguments addObject:[NSString stringWithUTF8String:aArgv[i]]]; } - NSTask* child = [NSTask launchedTaskWithLaunchPath:launchPath arguments:arguments]; + NSTask* child = [NSTask launchedTaskWithLaunchPath:launchPath + arguments:arguments]; if (aPid) { *aPid = [child processIdentifier]; // We used to use waitpid to wait for the process to terminate. This is @@ -43,31 +44,36 @@ bool InstallPrivilegedHelper() { AuthorizationRef authRef = NULL; OSStatus status = AuthorizationCreate( NULL, kAuthorizationEmptyEnvironment, - kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed, &authRef); + kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed, + &authRef); if (status != errAuthorizationSuccess) { // AuthorizationCreate really shouldn't fail. - NSLog(@"AuthorizationCreate failed! NSOSStatusErrorDomain / %d", (int)status); + NSLog(@"AuthorizationCreate failed! NSOSStatusErrorDomain / %d", + (int)status); return NO; } BOOL result = NO; AuthorizationItem authItem = {kSMRightBlessPrivilegedHelper, 0, NULL, 0}; AuthorizationRights authRights = {1, &authItem}; - AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | - kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights; + AuthorizationFlags flags = + kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | + kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights; // Obtain the right to install our privileged helper tool. - status = - AuthorizationCopyRights(authRef, &authRights, kAuthorizationEmptyEnvironment, flags, NULL); + status = AuthorizationCopyRights(authRef, &authRights, + kAuthorizationEmptyEnvironment, flags, NULL); if (status != errAuthorizationSuccess) { - NSLog(@"AuthorizationCopyRights failed! NSOSStatusErrorDomain / %d", (int)status); + NSLog(@"AuthorizationCopyRights failed! NSOSStatusErrorDomain / %d", + (int)status); } else { CFErrorRef cfError; // This does all the work of verifying the helper tool against the // application and vice-versa. Once verification has passed, the embedded // launchd.plist is extracted and placed in /Library/LaunchDaemons and then // loaded. The executable is placed in /Library/PrivilegedHelperTools. - result = (BOOL)SMJobBless(kSMDomainSystemLaunchd, (CFStringRef) @"org.mozilla.updater", authRef, + result = (BOOL)SMJobBless(kSMDomainSystemLaunchd, + (CFStringRef) @"org.mozilla.updater", authRef, &cfError); if (!result) { NSLog(@"Unable to install helper!"); @@ -90,7 +96,8 @@ void AbortElevatedUpdate() { updateServer = (id)[NSConnection rootProxyForConnectionWithRegisteredName:@"org.mozilla.updater.server" host:nil - usingNameServer:[NSSocketPortNameServer sharedInstance]]; + usingNameServer:[NSSocketPortNameServer + sharedInstance]]; if (updateServer && [updateServer respondsToSelector:@selector(abort)]) { [updateServer performSelector:@selector(abort)]; return; diff --git a/toolkit/xre/MacRunFromDmgUtils.mm b/toolkit/xre/MacRunFromDmgUtils.mm index 3e1982fc12e3..5cc38d6c1b97 100644 --- a/toolkit/xre/MacRunFromDmgUtils.mm +++ b/toolkit/xre/MacRunFromDmgUtils.mm @@ -59,30 +59,37 @@ static bool AskUserIfWeShouldLaunchExistingInstall() { ErrorResult rv; nsAutoCString mozTitle, mozMessage, mozLaunchExisting, mozLaunchFromDMG; - l10n->FormatValueSync("prompt-to-launch-existing-app-title"_ns, {}, mozTitle, rv); + l10n->FormatValueSync("prompt-to-launch-existing-app-title"_ns, {}, mozTitle, + rv); if (rv.Failed()) { return false; } - l10n->FormatValueSync("prompt-to-launch-existing-app-message"_ns, {}, mozMessage, rv); + l10n->FormatValueSync("prompt-to-launch-existing-app-message"_ns, {}, + mozMessage, rv); if (rv.Failed()) { return false; } - l10n->FormatValueSync("prompt-to-launch-existing-app-yes-button"_ns, {}, mozLaunchExisting, rv); + l10n->FormatValueSync("prompt-to-launch-existing-app-yes-button"_ns, {}, + mozLaunchExisting, rv); if (rv.Failed()) { return false; } - l10n->FormatValueSync("prompt-to-launch-existing-app-no-button"_ns, {}, mozLaunchFromDMG, rv); + l10n->FormatValueSync("prompt-to-launch-existing-app-no-button"_ns, {}, + mozLaunchFromDMG, rv); if (rv.Failed()) { return false; } - NSString* title = [NSString stringWithUTF8String:reinterpret_cast(mozTitle.get())]; - NSString* message = - [NSString stringWithUTF8String:reinterpret_cast(mozMessage.get())]; + NSString* title = [NSString + stringWithUTF8String:reinterpret_cast(mozTitle.get())]; + NSString* message = [NSString + stringWithUTF8String:reinterpret_cast(mozMessage.get())]; NSString* launchExisting = - [NSString stringWithUTF8String:reinterpret_cast(mozLaunchExisting.get())]; + [NSString stringWithUTF8String:reinterpret_cast( + mozLaunchExisting.get())]; NSString* launchFromDMG = - [NSString stringWithUTF8String:reinterpret_cast(mozLaunchFromDMG.get())]; + [NSString stringWithUTF8String:reinterpret_cast( + mozLaunchFromDMG.get())]; NSAlert* alert = [[[NSAlert alloc] init] autorelease]; @@ -144,18 +151,20 @@ static bool AskUserIfWeShouldInstall() { if (rv.Failed()) { return false; } - l10n->FormatValueSync("prompt-to-install-no-button"_ns, {}, mozDontInstall, rv); + l10n->FormatValueSync("prompt-to-install-no-button"_ns, {}, mozDontInstall, + rv); if (rv.Failed()) { return false; } - NSString* title = [NSString stringWithUTF8String:reinterpret_cast(mozTitle.get())]; - NSString* message = - [NSString stringWithUTF8String:reinterpret_cast(mozMessage.get())]; - NSString* install = - [NSString stringWithUTF8String:reinterpret_cast(mozInstall.get())]; - NSString* dontInstall = - [NSString stringWithUTF8String:reinterpret_cast(mozDontInstall.get())]; + NSString* title = [NSString + stringWithUTF8String:reinterpret_cast(mozTitle.get())]; + NSString* message = [NSString + stringWithUTF8String:reinterpret_cast(mozMessage.get())]; + NSString* install = [NSString + stringWithUTF8String:reinterpret_cast(mozInstall.get())]; + NSString* dontInstall = [NSString + stringWithUTF8String:reinterpret_cast(mozDontInstall.get())]; NSAlert* alert = [[[NSAlert alloc] init] autorelease]; @@ -179,15 +188,15 @@ static bool AskUserIfWeShouldInstall() { // AskUserIfWeShouldInstall // | // | ---> [NSApp run] - // | | - // | | -----> task - // | | | -----------> [alert runModal] - // | | | | (User selects button) - // | | | <--------------- done - // | | | - // | | | -----------> [NSApp stop:nil] - // | | | <----------- - // | | <-------- + // | | + // | | ---> task + // | | | ----> [alert runModal] + // | | | | (User selects button) + // | | | <--------- done + // | | | + // | | | -----> [NSApp stop:nil] + // | | | <----- + // | | <----- // | <------- // done __block NSInteger result = -1; @@ -225,9 +234,10 @@ static void ShowInstallFailedDialog() { return; } - NSString* title = [NSString stringWithUTF8String:reinterpret_cast(mozTitle.get())]; - NSString* message = - [NSString stringWithUTF8String:reinterpret_cast(mozMessage.get())]; + NSString* title = [NSString + stringWithUTF8String:reinterpret_cast(mozTitle.get())]; + NSString* message = [NSString + stringWithUTF8String:reinterpret_cast(mozMessage.get())]; NSAlert* alert = [[[NSAlert alloc] init] autorelease]; @@ -322,8 +332,9 @@ static bool InstallFromPath(NSString* aBundlePath, NSString* aDestPath) { NSString* destDir = [aDestPath stringByDeletingLastPathComponent]; if (!installSuccessful && ![fileManager isWritableFileAtPath:destDir]) { NSString* updaterBinPath = [NSString pathWithComponents:@[ - aBundlePath, @"Contents", @"MacOS", [NSString stringWithUTF8String:UPDATER_APP], @"Contents", - @"MacOS", [NSString stringWithUTF8String:UPDATER_BIN] + aBundlePath, @"Contents", @"MacOS", + [NSString stringWithUTF8String:UPDATER_APP], @"Contents", @"MacOS", + [NSString stringWithUTF8String:UPDATER_BIN] ]]; NSArray* arguments = @[ @"-dmgInstall", aBundlePath, aDestPath ]; @@ -354,7 +365,8 @@ static bool InstallFromPath(NSString* aBundlePath, NSString* aDestPath) { bool IsAppRunningFromDmg() { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - const char* path = [[[NSBundle mainBundle] bundlePath] fileSystemRepresentation]; + const char* path = + [[[NSBundle mainBundle] bundlePath] fileSystemRepresentation]; struct statfs statfsBuf; if (statfs(path, &statfsBuf) != 0) { @@ -388,11 +400,13 @@ bool IsAppRunningFromDmg() { // Get the IOMedia object: // (Note: IOServiceGetMatchingServices takes ownership of serviceDict's ref.) - CFMutableDictionaryRef serviceDict = IOBSDNameMatching(kIOMasterPortDefault, 0, bsdDeviceName); + CFMutableDictionaryRef serviceDict = + IOBSDNameMatching(kIOMasterPortDefault, 0, bsdDeviceName); if (!serviceDict) { return false; } - io_service_t media = IOServiceGetMatchingService(kIOMasterPortDefault, serviceDict); + io_service_t media = + IOServiceGetMatchingService(kIOMasterPortDefault, serviceDict); if (!media || !IOObjectConformsTo(media, "IOMedia")) { return false; } @@ -401,14 +415,16 @@ bool IsAppRunningFromDmg() { // (taking care to start with `media` itself): io_service_t imageDrive = IO_OBJECT_NULL; io_iterator_t iter; - if (IORegistryEntryCreateIterator(media, kIOServicePlane, - kIORegistryIterateRecursively | kIORegistryIterateParents, - &iter) != KERN_SUCCESS) { + if (IORegistryEntryCreateIterator( + media, kIOServicePlane, + kIORegistryIterateRecursively | kIORegistryIterateParents, + &iter) != KERN_SUCCESS) { IOObjectRelease(media); return false; } - const char* imageClass = - nsCocoaFeatures::OnMontereyOrLater() ? "AppleDiskImageDevice" : "IOHDIXHDDrive"; + const char* imageClass = nsCocoaFeatures::OnMontereyOrLater() + ? "AppleDiskImageDevice" + : "IOHDIXHDDrive"; for (imageDrive = media; imageDrive; imageDrive = IOIteratorNext(iter)) { if (IOObjectConformsTo(imageDrive, imageClass)) { break; @@ -446,20 +462,22 @@ bool MaybeInstallAndRelaunch() { // The Applications directory may not be at /Applications, although in // practice we're unlikely to encounter since run-from-.dmg is really an // issue with novice mac users. Still, look it up correctly: - NSArray* applicationsDirs = - NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSLocalDomainMask, YES); + NSArray* applicationsDirs = NSSearchPathForDirectoriesInDomains( + NSApplicationDirectory, NSLocalDomainMask, YES); NSString* applicationsDir = applicationsDirs[0]; // Sanity check dir exists NSFileManager* fileManager = [NSFileManager defaultManager]; BOOL isDir; - if (![fileManager fileExistsAtPath:applicationsDir isDirectory:&isDir] || !isDir) { + if (![fileManager fileExistsAtPath:applicationsDir isDirectory:&isDir] || + !isDir) { return false; } NSString* bundlePath = [[NSBundle mainBundle] bundlePath]; NSString* appName = [bundlePath lastPathComponent]; - NSString* destPath = [applicationsDir stringByAppendingPathComponent:appName]; + NSString* destPath = + [applicationsDir stringByAppendingPathComponent:appName]; // If the app (an app of the same name) is already installed we can't really // tell without asking if we're dealing with the edge case of an diff --git a/toolkit/xre/UIKitDirProvider.mm b/toolkit/xre/UIKitDirProvider.mm index 043ecbe2ecc9..cd19b41266b6 100644 --- a/toolkit/xre/UIKitDirProvider.mm +++ b/toolkit/xre/UIKitDirProvider.mm @@ -8,8 +8,10 @@ #include "UIKitDirProvider.h" bool GetUIKitDirectory(bool aLocal, nsACString& aUserDir) { - NSSearchPathDirectory directory = aLocal ? NSCachesDirectory : NSApplicationSupportDirectory; - NSArray* paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES); + NSSearchPathDirectory directory = + aLocal ? NSCachesDirectory : NSApplicationSupportDirectory; + NSArray* paths = + NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES); if ([paths count] == 0) { return false; } diff --git a/toolkit/xre/nsCommandLineServiceMac.mm b/toolkit/xre/nsCommandLineServiceMac.mm index e143a41fad18..6a8e79f9eaaf 100644 --- a/toolkit/xre/nsCommandLineServiceMac.mm +++ b/toolkit/xre/nsCommandLineServiceMac.mm @@ -21,8 +21,8 @@ static bool sBuildingCommandLine = false; void AddToCommandLine(const char* inArgText) { if (sArgsUsed >= sArgsAllocated - 1) { // realloc does not free the given pointer if allocation fails - char** temp = - static_cast(realloc(sArgs, (sArgsAllocated + kArgsGrowSize) * sizeof(char*))); + char** temp = static_cast( + realloc(sArgs, (sArgsAllocated + kArgsGrowSize) * sizeof(char*))); if (!temp) return; sArgs = temp; sArgsAllocated += kArgsGrowSize; @@ -67,7 +67,8 @@ void SetupMacCommandLine(int& argc, char**& argv, bool forRestart) { // if the parent is in the foreground. This will be communicated in a // command-line argument to the child. if (forRestart) { - NSRunningApplication* frontApp = [[NSWorkspace sharedWorkspace] frontmostApplication]; + NSRunningApplication* frontApp = + [[NSWorkspace sharedWorkspace] frontmostApplication]; if ([frontApp isEqual:[NSRunningApplication currentApplication]]) { AddToCommandLine("-foreground"); } diff --git a/toolkit/xre/nsNativeAppSupportCocoa.mm b/toolkit/xre/nsNativeAppSupportCocoa.mm index 1fe480b6995e..6f4b96b88d2c 100644 --- a/toolkit/xre/nsNativeAppSupportCocoa.mm +++ b/toolkit/xre/nsNativeAppSupportCocoa.mm @@ -119,7 +119,8 @@ nsNativeAppSupportCocoa::ReOpen() { windowList->HasMoreElements(&more); continue; } - NSWindow* cocoaWindow = (NSWindow*)widget->GetNativeData(NS_NATIVE_WINDOW); + NSWindow* cocoaWindow = + (NSWindow*)widget->GetNativeData(NS_NATIVE_WINDOW); if (![cocoaWindow isMiniaturized]) { haveNonMiniaturized = true; break; // have un-minimized windows, nothing to do @@ -154,7 +155,8 @@ nsNativeAppSupportCocoa::ReOpen() { nsCOMPtr cmdLine(new nsCommandLine()); nsresult rv; - rv = cmdLine->Init(0, argv, nullptr, nsICommandLine::STATE_REMOTE_EXPLICIT); + rv = cmdLine->Init(0, argv, nullptr, + nsICommandLine::STATE_REMOTE_EXPLICIT); NS_ENSURE_SUCCESS(rv, rv); return cmdLine->Run(); diff --git a/toolkit/xre/updaterfileutils_osx.mm b/toolkit/xre/updaterfileutils_osx.mm index 15a4b3a5bacf..25f14f3734f9 100644 --- a/toolkit/xre/updaterfileutils_osx.mm +++ b/toolkit/xre/updaterfileutils_osx.mm @@ -13,8 +13,10 @@ bool IsRecursivelyWritable(const char* aPath) { NSString* rootPath = [NSString stringWithUTF8String:aPath]; NSFileManager* fileManager = [NSFileManager defaultManager]; NSError* error = nil; - NSArray* subPaths = [fileManager subpathsOfDirectoryAtPath:rootPath error:&error]; - NSMutableArray* paths = [NSMutableArray arrayWithCapacity:[subPaths count] + 1]; + NSArray* subPaths = [fileManager subpathsOfDirectoryAtPath:rootPath + error:&error]; + NSMutableArray* paths = + [NSMutableArray arrayWithCapacity:[subPaths count] + 1]; [paths addObject:@""]; [paths addObjectsFromArray:subPaths]; @@ -26,7 +28,8 @@ bool IsRecursivelyWritable(const char* aPath) { for (NSString* currPath in paths) { NSString* child = [rootPath stringByAppendingPathComponent:currPath]; - NSDictionary* attributes = [fileManager attributesOfItemAtPath:child error:&error]; + NSDictionary* attributes = [fileManager attributesOfItemAtPath:child + error:&error]; if (error) { [pool drain]; return false; diff --git a/uriloader/exthandler/mac/nsLocalHandlerAppMac.mm b/uriloader/exthandler/mac/nsLocalHandlerAppMac.mm index d6ad85a24e79..07f0276666b5 100644 --- a/uriloader/exthandler/mac/nsLocalHandlerAppMac.mm +++ b/uriloader/exthandler/mac/nsLocalHandlerAppMac.mm @@ -10,7 +10,8 @@ #include "nsILocalFileMac.h" #include "nsIURI.h" -// We override this to make sure app bundles display their pretty name (without .app suffix) +// We override this to make sure app bundles display their pretty name (without +// .app suffix) NS_IMETHODIMP nsLocalHandlerAppMac::GetName(nsAString& aName) { if (mExecutable) { nsCOMPtr macFile = do_QueryInterface(mExecutable); @@ -30,7 +31,8 @@ NS_IMETHODIMP nsLocalHandlerAppMac::GetName(nsAString& aName) { * somewhere more central (see bug 389922). */ NS_IMETHODIMP -nsLocalHandlerAppMac::LaunchWithURI(nsIURI* aURI, mozilla::dom::BrowsingContext* aBrowsingContext) { +nsLocalHandlerAppMac::LaunchWithURI( + nsIURI* aURI, mozilla::dom::BrowsingContext* aBrowsingContext) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; nsresult rv; @@ -45,14 +47,15 @@ nsLocalHandlerAppMac::LaunchWithURI(nsIURI* aURI, mozilla::dom::BrowsingContext* aURI->GetAsciiSpec(uriSpec); const UInt8* uriString = reinterpret_cast(uriSpec.get()); - CFURLRef uri = - ::CFURLCreateWithBytes(NULL, uriString, uriSpec.Length(), kCFStringEncodingUTF8, NULL); + CFURLRef uri = ::CFURLCreateWithBytes(NULL, uriString, uriSpec.Length(), + kCFStringEncodingUTF8, NULL); if (!uri) { ::CFRelease(appURL); return NS_ERROR_OUT_OF_MEMORY; } - CFArrayRef uris = ::CFArrayCreate(NULL, reinterpret_cast(&uri), 1, NULL); + CFArrayRef uris = + ::CFArrayCreate(NULL, reinterpret_cast(&uri), 1, NULL); if (!uris) { ::CFRelease(uri); ::CFRelease(appURL); diff --git a/uriloader/exthandler/mac/nsMIMEInfoMac.mm b/uriloader/exthandler/mac/nsMIMEInfoMac.mm index 09fe525eec07..33dd9d1ee0cc 100644 --- a/uriloader/exthandler/mac/nsMIMEInfoMac.mm +++ b/uriloader/exthandler/mac/nsMIMEInfoMac.mm @@ -11,8 +11,10 @@ #include "nsMIMEInfoMac.h" #include "nsILocalFileMac.h" -// We override this to make sure app bundles display their pretty name (without .app suffix) -NS_IMETHODIMP nsMIMEInfoMac::GetDefaultDescription(nsAString& aDefaultDescription) { +// We override this to make sure app bundles display their pretty name (without +// .app suffix) +NS_IMETHODIMP nsMIMEInfoMac::GetDefaultDescription( + nsAString& aDefaultDescription) { nsCOMPtr defaultApp = GetDefaultApplication(); if (defaultApp) { nsCOMPtr macFile = do_QueryInterface(defaultApp); @@ -43,7 +45,8 @@ nsMIMEInfoMac::LaunchWithFile(nsIFile* aFile) { if (mPreferredAction == useHelperApp) { // we don't yet support passing content by value (rather than reference) // to web apps. at some point, we will probably want to. - nsCOMPtr localHandlerApp = do_QueryInterface(mPreferredApplication, &rv); + nsCOMPtr localHandlerApp = + do_QueryInterface(mPreferredApplication, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = localHandlerApp->GetExecutable(getter_AddRefs(application)); @@ -68,7 +71,8 @@ nsMIMEInfoMac::LaunchWithFile(nsIFile* aFile) { tempFile->GetFSRef(&tempFileRef); FSRef appFSRef; - if (::LSGetApplicationForItem(&tempFileRef, kLSRolesAll, &appFSRef, nullptr) == noErr) { + if (::LSGetApplicationForItem(&tempFileRef, kLSRolesAll, &appFSRef, + nullptr) == noErr) { app = (do_CreateInstance("@mozilla.org/file/local;1")); if (!app) return NS_ERROR_FAILURE; app->InitWithFSRef(&appFSRef); @@ -91,8 +95,9 @@ nsresult nsMIMEInfoMac::LoadUriInternal(nsIURI* aURI) { nsAutoCString uri; aURI->GetSpec(uri); if (!uri.IsEmpty()) { - CFURLRef myURLRef = ::CFURLCreateWithBytes(kCFAllocatorDefault, (const UInt8*)uri.get(), - strlen(uri.get()), kCFStringEncodingUTF8, NULL); + CFURLRef myURLRef = + ::CFURLCreateWithBytes(kCFAllocatorDefault, (const UInt8*)uri.get(), + strlen(uri.get()), kCFStringEncodingUTF8, NULL); if (myURLRef) { OSStatus status = ::LSOpenCFURLRef(myURLRef, NULL); if (status == noErr) rv = NS_OK; diff --git a/uriloader/exthandler/mac/nsOSHelperAppService.mm b/uriloader/exthandler/mac/nsOSHelperAppService.mm index 8117e01c2cd3..602c2a89d53d 100644 --- a/uriloader/exthandler/mac/nsOSHelperAppService.mm +++ b/uriloader/exthandler/mac/nsOSHelperAppService.mm @@ -25,7 +25,8 @@ #import // chrome URL's -#define HELPERAPPLAUNCHER_BUNDLE_URL "chrome://global/locale/helperAppLauncher.properties" +#define HELPERAPPLAUNCHER_BUNDLE_URL \ + "chrome://global/locale/helperAppLauncher.properties" #define BRAND_BUNDLE_URL "chrome://branding/locale/brand.properties" nsresult GetDefaultBundleURL(const nsACString& aScheme, CFURLRef* aBundleURL) { @@ -34,18 +35,20 @@ nsresult GetDefaultBundleURL(const nsACString& aScheme, CFURLRef* aBundleURL) { nsresult rv = NS_ERROR_NOT_AVAILABLE; CFStringRef schemeCFString = ::CFStringCreateWithBytes( - kCFAllocatorDefault, (const UInt8*)PromiseFlatCString(aScheme).get(), aScheme.Length(), - kCFStringEncodingUTF8, false); + kCFAllocatorDefault, (const UInt8*)PromiseFlatCString(aScheme).get(), + aScheme.Length(), kCFStringEncodingUTF8, false); if (schemeCFString) { CFStringRef lookupCFString = ::CFStringCreateWithFormat(NULL, NULL, CFSTR("%@:"), schemeCFString); if (lookupCFString) { - CFURLRef lookupCFURL = ::CFURLCreateWithString(NULL, lookupCFString, NULL); + CFURLRef lookupCFURL = + ::CFURLCreateWithString(NULL, lookupCFString, NULL); if (lookupCFURL) { - *aBundleURL = ::LSCopyDefaultApplicationURLForURL(lookupCFURL, kLSRolesAll, NULL); + *aBundleURL = + ::LSCopyDefaultApplicationURLForURL(lookupCFURL, kLSRolesAll, NULL); if (*aBundleURL) { rv = NS_OK; } @@ -88,15 +91,15 @@ using mozilla::LogLevel; nsOSHelperAppService::~nsOSHelperAppService() {} -nsresult nsOSHelperAppService::OSProtocolHandlerExists(const char* aProtocolScheme, - bool* aHandlerExists) { +nsresult nsOSHelperAppService::OSProtocolHandlerExists( + const char* aProtocolScheme, bool* aHandlerExists) { // CFStringCreateWithBytes() can fail even if we're not out of memory -- // for example if the 'bytes' parameter is something very weird (like // "\xFF\xFF~"), or possibly if it can't be interpreted as using what's // specified in the 'encoding' parameter. See bug 548719. - CFStringRef schemeString = - ::CFStringCreateWithBytes(kCFAllocatorDefault, (const UInt8*)aProtocolScheme, - strlen(aProtocolScheme), kCFStringEncodingUTF8, false); + CFStringRef schemeString = ::CFStringCreateWithBytes( + kCFAllocatorDefault, (const UInt8*)aProtocolScheme, + strlen(aProtocolScheme), kCFStringEncodingUTF8, false); if (schemeString) { // LSCopyDefaultHandlerForURLScheme() can fail to find the default handler // for aProtocolScheme when it's never been explicitly set (using @@ -118,8 +121,8 @@ nsresult nsOSHelperAppService::OSProtocolHandlerExists(const char* aProtocolSche return NS_OK; } -NS_IMETHODIMP nsOSHelperAppService::GetApplicationDescription(const nsACString& aScheme, - nsAString& _retval) { +NS_IMETHODIMP nsOSHelperAppService::GetApplicationDescription( + const nsACString& aScheme, nsAString& _retval) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; nsresult rv = NS_ERROR_NOT_AVAILABLE; @@ -136,14 +139,17 @@ NS_IMETHODIMP nsOSHelperAppService::GetApplicationDescription(const nsACString& // Get the human-readable name of the bundle CFStringRef bundleName = - (CFStringRef)::CFBundleGetValueForInfoDictionaryKey(handlerBundle, kCFBundleNameKey); + (CFStringRef)::CFBundleGetValueForInfoDictionaryKey(handlerBundle, + kCFBundleNameKey); if (bundleName) { AutoTArray buffer; CFIndex bundleNameLength = ::CFStringGetLength(bundleName); buffer.SetLength(bundleNameLength); - ::CFStringGetCharacters(bundleName, CFRangeMake(0, bundleNameLength), buffer.Elements()); - _retval.Assign(reinterpret_cast(buffer.Elements()), bundleNameLength); + ::CFStringGetCharacters(bundleName, CFRangeMake(0, bundleNameLength), + buffer.Elements()); + _retval.Assign(reinterpret_cast(buffer.Elements()), + bundleNameLength); rv = NS_OK; } ::CFRelease(handlerBundle); @@ -155,8 +161,8 @@ NS_IMETHODIMP nsOSHelperAppService::GetApplicationDescription(const nsACString& NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -NS_IMETHODIMP nsOSHelperAppService::IsCurrentAppOSDefaultForProtocol(const nsACString& aScheme, - bool* _retval) { +NS_IMETHODIMP nsOSHelperAppService::IsCurrentAppOSDefaultForProtocol( + const nsACString& aScheme, bool* _retval) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; nsresult rv = NS_ERROR_NOT_AVAILABLE; @@ -164,7 +170,8 @@ NS_IMETHODIMP nsOSHelperAppService::IsCurrentAppOSDefaultForProtocol(const nsACS CFURLRef handlerBundleURL; rv = GetDefaultBundleURL(aScheme, &handlerBundleURL); if (NS_SUCCEEDED(rv) && handlerBundleURL) { - // Ensure we don't accidentally return success if we can't get an app bundle. + // Ensure we don't accidentally return success if we can't get an app + // bundle. rv = NS_ERROR_NOT_AVAILABLE; CFBundleRef appBundle = ::CFBundleGetMainBundle(); if (appBundle) { @@ -181,23 +188,25 @@ NS_IMETHODIMP nsOSHelperAppService::IsCurrentAppOSDefaultForProtocol(const nsACS NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -nsresult nsOSHelperAppService::GetFileTokenForPath(const char16_t* aPlatformAppPath, - nsIFile** aFile) { +nsresult nsOSHelperAppService::GetFileTokenForPath( + const char16_t* aPlatformAppPath, nsIFile** aFile) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; nsresult rv; - nsCOMPtr localFile(do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv)); + nsCOMPtr localFile( + do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv)); NS_ENSURE_SUCCESS(rv, rv); CFURLRef pathAsCFURL; CFStringRef pathAsCFString = ::CFStringCreateWithCharacters( - NULL, reinterpret_cast(aPlatformAppPath), NS_strlen(aPlatformAppPath)); + NULL, reinterpret_cast(aPlatformAppPath), + NS_strlen(aPlatformAppPath)); if (!pathAsCFString) return NS_ERROR_OUT_OF_MEMORY; if (::CFStringGetCharacterAtIndex(pathAsCFString, 0) == '/') { // we have a Posix path - pathAsCFURL = - ::CFURLCreateWithFileSystemPath(nullptr, pathAsCFString, kCFURLPOSIXPathStyle, false); + pathAsCFURL = ::CFURLCreateWithFileSystemPath(nullptr, pathAsCFString, + kCFURLPOSIXPathStyle, false); if (!pathAsCFURL) { ::CFRelease(pathAsCFString); return NS_ERROR_OUT_OF_MEMORY; @@ -214,8 +223,8 @@ nsresult nsOSHelperAppService::GetFileTokenForPath(const char16_t* aPlatformAppP return NS_ERROR_FILE_UNRECOGNIZED_PATH; } - pathAsCFURL = - ::CFURLCreateWithFileSystemPath(nullptr, pathAsCFString, kCFURLHFSPathStyle, false); + pathAsCFURL = ::CFURLCreateWithFileSystemPath(nullptr, pathAsCFString, + kCFURLHFSPathStyle, false); if (!pathAsCFURL) { ::CFRelease(pathAsCFString); return NS_ERROR_OUT_OF_MEMORY; @@ -259,7 +268,8 @@ static CFArrayRef GetMIMETypesHandledByApp(FSRef* aAppRef) { if (!infoDict) { return NULL; } - CFTypeRef cfObject = ::CFDictionaryGetValue(infoDict, CFSTR("CFBundleDocumentTypes")); + CFTypeRef cfObject = + ::CFDictionaryGetValue(infoDict, CFSTR("CFBundleDocumentTypes")); if (!cfObject || (::CFGetTypeID(cfObject) != ::CFArrayGetTypeID())) { ::CFRelease(infoDict); return NULL; @@ -307,7 +317,8 @@ static CFArrayRef GetMIMETypesHandledByApp(FSRef* aAppRef) { } nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, - const nsACString& aFileExt, bool* aFound, + const nsACString& aFileExt, + bool* aFound, nsIMIMEInfo** aMIMEInfo) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; MOZ_ASSERT(XRE_IsParentProcess()); @@ -318,7 +329,8 @@ nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, const nsCString& flatExt = PromiseFlatCString(aFileExt); MOZ_LOG(sLog, LogLevel::Debug, - ("Mac: HelperAppService lookup for type '%s' ext '%s'\n", flatType.get(), flatExt.get())); + ("Mac: HelperAppService lookup for type '%s' ext '%s'\n", + flatType.get(), flatExt.get())); // Create a Mac-specific MIME info so we can use Mac-specific members. RefPtr mimeInfoMac = new nsMIMEInfoMac(aMIMEType); @@ -337,13 +349,15 @@ nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, CFStringRef cfMIMEType = NULL; if (!aMIMEType.IsEmpty()) { - typeIsOctetStream = aMIMEType.LowerCaseEqualsLiteral(APPLICATION_OCTET_STREAM); + typeIsOctetStream = + aMIMEType.LowerCaseEqualsLiteral(APPLICATION_OCTET_STREAM); CFURLRef appURL = NULL; // CFStringCreateWithCString() can fail even if we're not out of memory -- // for example if the 'cStr' parameter is something very weird (like // "\xFF\xFF~"), or possibly if it can't be interpreted as using what's // specified in the 'encoding' parameter. See bug 548719. - cfMIMEType = ::CFStringCreateWithCString(NULL, flatType.get(), kCFStringEncodingUTF8); + cfMIMEType = ::CFStringCreateWithCString(NULL, flatType.get(), + kCFStringEncodingUTF8); if (cfMIMEType) { err = ::LSCopyApplicationForMIMEType(cfMIMEType, kLSRolesAll, &appURL); if ((err == noErr) && appURL && ::CFURLGetFSRef(appURL, &typeAppFSRef)) { @@ -361,13 +375,15 @@ nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, // for example if the 'cStr' parameter is something very weird (like // "\xFF\xFF~"), or possibly if it can't be interpreted as using what's // specified in the 'encoding' parameter. See bug 548719. - CFStringRef cfExt = ::CFStringCreateWithCString(NULL, flatExt.get(), kCFStringEncodingUTF8); + CFStringRef cfExt = + ::CFStringCreateWithCString(NULL, flatExt.get(), kCFStringEncodingUTF8); if (cfExt) { - err = ::LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, cfExt, kLSRolesAll, - &extAppFSRef, nullptr); + err = ::LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, cfExt, + kLSRolesAll, &extAppFSRef, nullptr); if (err == noErr) { haveAppForExt = true; - MOZ_LOG(sLog, LogLevel::Debug, ("LSGetApplicationForInfo found a default application\n")); + MOZ_LOG(sLog, LogLevel::Debug, + ("LSGetApplicationForInfo found a default application\n")); } ::CFRelease(cfExt); } @@ -375,7 +391,8 @@ nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, if (haveAppForType && haveAppForExt) { // Do aMIMEType and aFileExt match? - if (::FSCompareFSRefs((const FSRef*)&typeAppFSRef, (const FSRef*)&extAppFSRef) == noErr) { + if (::FSCompareFSRefs((const FSRef*)&typeAppFSRef, + (const FSRef*)&extAppFSRef) == noErr) { typeAppIsDefault = true; *aFound = true; } @@ -418,9 +435,10 @@ nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, CFArrayRef extAppMIMETypes = GetMIMETypesHandledByApp(&extAppFSRef); if (extAppMIMETypes) { if (cfMIMEType) { - if (::CFArrayContainsValue(extAppMIMETypes, - ::CFRangeMake(0, ::CFArrayGetCount(extAppMIMETypes)), - cfMIMEType)) { + if (::CFArrayContainsValue( + extAppMIMETypes, + ::CFRangeMake(0, ::CFArrayGetCount(extAppMIMETypes)), + cfMIMEType)) { extAppIsDefault = true; *aFound = true; } @@ -445,11 +463,13 @@ nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, // the doc for this method says that if we have a MIME type (in // aMIMEType), we need to give it preference.) NSURLFileTypeMappings* map = [NSURLFileTypeMappings sharedMappings]; - NSString* extStr = [NSString stringWithCString:flatExt.get() encoding:NSASCIIStringEncoding]; + NSString* extStr = [NSString stringWithCString:flatExt.get() + encoding:NSASCIIStringEncoding]; NSString* typeStr = map ? [map MIMETypeForExtension:extStr] : NULL; if (typeStr) { nsAutoCString mimeType; - mimeType.Assign((char*)[typeStr cStringUsingEncoding:NSASCIIStringEncoding]); + mimeType.Assign( + (char*)[typeStr cStringUsingEncoding:NSASCIIStringEncoding]); mimeInfoMac->SetMIMEType(mimeType); haveAppForType = true; } else { @@ -476,7 +496,8 @@ nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, if (haveAppForExt) mimeInfoMac->AppendExtension(aFileExt); nsresult rv; - nsCOMPtr app(do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv)); + nsCOMPtr app( + do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv)); if (NS_FAILED(rv)) { [localPool release]; return rv; @@ -485,20 +506,22 @@ nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, CFStringRef cfAppName = NULL; if (typeAppIsDefault) { app->InitWithFSRef(&typeAppFSRef); - ::LSCopyItemAttribute((const FSRef*)&typeAppFSRef, kLSRolesAll, kLSItemDisplayName, - (CFTypeRef*)&cfAppName); + ::LSCopyItemAttribute((const FSRef*)&typeAppFSRef, kLSRolesAll, + kLSItemDisplayName, (CFTypeRef*)&cfAppName); } else { app->InitWithFSRef(&extAppFSRef); - ::LSCopyItemAttribute((const FSRef*)&extAppFSRef, kLSRolesAll, kLSItemDisplayName, - (CFTypeRef*)&cfAppName); + ::LSCopyItemAttribute((const FSRef*)&extAppFSRef, kLSRolesAll, + kLSItemDisplayName, (CFTypeRef*)&cfAppName); } if (cfAppName) { AutoTArray buffer; CFIndex appNameLength = ::CFStringGetLength(cfAppName); buffer.SetLength(appNameLength); - ::CFStringGetCharacters(cfAppName, CFRangeMake(0, appNameLength), buffer.Elements()); + ::CFStringGetCharacters(cfAppName, CFRangeMake(0, appNameLength), + buffer.Elements()); nsAutoString appName; - appName.Assign(reinterpret_cast(buffer.Elements()), appNameLength); + appName.Assign(reinterpret_cast(buffer.Elements()), + appNameLength); mimeInfoMac->SetDefaultDescription(appName); ::CFRelease(cfAppName); } @@ -516,25 +539,29 @@ nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, // If we have a MIME type, make sure its extension list is included in our // list. NSURLFileTypeMappings* map = [NSURLFileTypeMappings sharedMappings]; - NSString* typeStr = [NSString stringWithCString:mimeType.get() encoding:NSASCIIStringEncoding]; + NSString* typeStr = [NSString stringWithCString:mimeType.get() + encoding:NSASCIIStringEncoding]; NSArray* extensionsList = map ? [map extensionsForMIMEType:typeStr] : NULL; if (extensionsList) { for (NSString* extension in extensionsList) { nsAutoCString ext; - ext.Assign((char*)[extension cStringUsingEncoding:NSASCIIStringEncoding]); + ext.Assign( + (char*)[extension cStringUsingEncoding:NSASCIIStringEncoding]); mimeInfoMac->AppendExtension(ext); } } - if (CFStringRef cfType = - ::CFStringCreateWithCString(NULL, mimeType.get(), kCFStringEncodingUTF8)) { + if (CFStringRef cfType = ::CFStringCreateWithCString( + NULL, mimeType.get(), kCFStringEncodingUTF8)) { if (CFStringRef cfTypeDesc = ::UTTypeCopyDescription(cfType)) { AutoTArray buffer; CFIndex typeDescLength = ::CFStringGetLength(cfTypeDesc); buffer.SetLength(typeDescLength); - ::CFStringGetCharacters(cfTypeDesc, CFRangeMake(0, typeDescLength), buffer.Elements()); + ::CFStringGetCharacters(cfTypeDesc, CFRangeMake(0, typeDescLength), + buffer.Elements()); nsAutoString typeDesc; - typeDesc.Assign(reinterpret_cast(buffer.Elements()), typeDescLength); + typeDesc.Assign(reinterpret_cast(buffer.Elements()), + typeDescLength); mimeInfoMac->SetDescription(typeDesc); ::CFRelease(cfTypeDesc); } @@ -542,7 +569,8 @@ nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, } } - MOZ_LOG(sLog, LogLevel::Debug, ("OS gave us: type '%s' found '%i'\n", mimeType.get(), *aFound)); + MOZ_LOG(sLog, LogLevel::Debug, + ("OS gave us: type '%s' found '%i'\n", mimeType.get(), *aFound)); [localPool release]; mimeInfoMac.forget(aMIMEInfo); @@ -552,14 +580,17 @@ nsresult nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, } NS_IMETHODIMP -nsOSHelperAppService::GetProtocolHandlerInfoFromOS(const nsACString& aScheme, bool* found, +nsOSHelperAppService::GetProtocolHandlerInfoFromOS(const nsACString& aScheme, + bool* found, nsIHandlerInfo** _retval) { NS_ASSERTION(!aScheme.IsEmpty(), "No scheme was specified!"); - nsresult rv = OSProtocolHandlerExists(nsPromiseFlatCString(aScheme).get(), found); + nsresult rv = + OSProtocolHandlerExists(nsPromiseFlatCString(aScheme).get(), found); if (NS_FAILED(rv)) return rv; - nsMIMEInfoMac* handlerInfo = new nsMIMEInfoMac(aScheme, nsMIMEInfoBase::eProtocolInfo); + nsMIMEInfoMac* handlerInfo = + new nsMIMEInfoMac(aScheme, nsMIMEInfoBase::eProtocolInfo); NS_ENSURE_TRUE(handlerInfo, NS_ERROR_OUT_OF_MEMORY); NS_ADDREF(*_retval = handlerInfo); diff --git a/uriloader/exthandler/uikit/nsLocalHandlerAppUIKit.mm b/uriloader/exthandler/uikit/nsLocalHandlerAppUIKit.mm index ae6697f9b6c0..6f70e035bbd1 100644 --- a/uriloader/exthandler/uikit/nsLocalHandlerAppUIKit.mm +++ b/uriloader/exthandler/uikit/nsLocalHandlerAppUIKit.mm @@ -10,7 +10,7 @@ #include "nsIURI.h" NS_IMETHODIMP -nsLocalHandlerAppUIKit::LaunchWithURI(nsIURI* aURI, - mozilla::dom::BrowsingContext* aBrowsingContext) { +nsLocalHandlerAppUIKit::LaunchWithURI( + nsIURI* aURI, mozilla::dom::BrowsingContext* aBrowsingContext) { return NS_ERROR_NOT_IMPLEMENTED; } diff --git a/uriloader/exthandler/uikit/nsMIMEInfoUIKit.mm b/uriloader/exthandler/uikit/nsMIMEInfoUIKit.mm index 2ed0c1eb2e7d..1226da220ece 100644 --- a/uriloader/exthandler/uikit/nsMIMEInfoUIKit.mm +++ b/uriloader/exthandler/uikit/nsMIMEInfoUIKit.mm @@ -7,6 +7,10 @@ #include "nsMIMEInfoUIKit.h" NS_IMETHODIMP -nsMIMEInfoUIKit::LaunchWithFile(nsIFile* aFile) { return NS_ERROR_NOT_IMPLEMENTED; } +nsMIMEInfoUIKit::LaunchWithFile(nsIFile* aFile) { + return NS_ERROR_NOT_IMPLEMENTED; +} -nsresult nsMIMEInfoUIKit::LoadUriInternal(nsIURI* aURI) { return NS_ERROR_NOT_IMPLEMENTED; } +nsresult nsMIMEInfoUIKit::LoadUriInternal(nsIURI* aURI) { + return NS_ERROR_NOT_IMPLEMENTED; +} diff --git a/uriloader/exthandler/uikit/nsOSHelperAppService.mm b/uriloader/exthandler/uikit/nsOSHelperAppService.mm index 5d6cc7b0fdb4..bfd83a583b67 100644 --- a/uriloader/exthandler/uikit/nsOSHelperAppService.mm +++ b/uriloader/exthandler/uikit/nsOSHelperAppService.mm @@ -10,43 +10,48 @@ nsOSHelperAppService::nsOSHelperAppService() : nsExternalHelperAppService() {} nsOSHelperAppService::~nsOSHelperAppService() {} -nsresult nsOSHelperAppService::OSProtocolHandlerExists(const char* aProtocolScheme, - bool* aHandlerExists) { +nsresult nsOSHelperAppService::OSProtocolHandlerExists( + const char* aProtocolScheme, bool* aHandlerExists) { *aHandlerExists = false; return NS_OK; } NS_IMETHODIMP -nsOSHelperAppService::GetApplicationDescription(const nsACString& aScheme, nsAString& _retval) { +nsOSHelperAppService::GetApplicationDescription(const nsACString& aScheme, + nsAString& _retval) { return NS_ERROR_NOT_AVAILABLE; } NS_IMETHODIMP -nsOSHelperAppService::IsCurrentAppOSDefaultForProtocol(const nsACString& aScheme, bool* _retval) { +nsOSHelperAppService::IsCurrentAppOSDefaultForProtocol( + const nsACString& aScheme, bool* _retval) { return NS_ERROR_NOT_AVAILABLE; } -nsresult nsOSHelperAppService::GetFileTokenForPath(const char16_t* aPlatformAppPath, - nsIFile** aFile) { +nsresult nsOSHelperAppService::GetFileTokenForPath( + const char16_t* aPlatformAppPath, nsIFile** aFile) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP -nsOSHelperAppService::GetFromTypeAndExtension(const nsACString& aType, const nsACString& aFileExt, +nsOSHelperAppService::GetFromTypeAndExtension(const nsACString& aType, + const nsACString& aFileExt, nsIMIMEInfo** aMIMEInfo) { - return nsExternalHelperAppService::GetFromTypeAndExtension(aType, aFileExt, aMIMEInfo); + return nsExternalHelperAppService::GetFromTypeAndExtension(aType, aFileExt, + aMIMEInfo); } -NS_IMETHODIMP nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType, - const nsACString& aFileExt, bool* aFound, - nsIMIMEInfo** aMIMEInfo) { +NS_IMETHODIMP nsOSHelperAppService::GetMIMEInfoFromOS( + const nsACString& aMIMEType, const nsACString& aFileExt, bool* aFound, + nsIMIMEInfo** aMIMEInfo) { *aMIMEInfo = nullptr; *aFound = false; return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP -nsOSHelperAppService::GetProtocolHandlerInfoFromOS(const nsACString& aScheme, bool* found, +nsOSHelperAppService::GetProtocolHandlerInfoFromOS(const nsACString& aScheme, + bool* found, nsIHandlerInfo** _retval) { *found = false; return NS_OK; diff --git a/widget/cocoa/AppearanceOverride.mm b/widget/cocoa/AppearanceOverride.mm index e335c2614580..36c17fd6cc8b 100644 --- a/widget/cocoa/AppearanceOverride.mm +++ b/widget/cocoa/AppearanceOverride.mm @@ -29,7 +29,8 @@ static void ToolbarThemePrefChanged(const char* aPref, void* aUserInfo); if (XRE_IsParentProcess()) { mozilla::Preferences::RegisterCallbackAndCall( &ToolbarThemePrefChanged, - nsDependentCString(mozilla::StaticPrefs::GetPrefName_browser_theme_toolbar_theme())); + nsDependentCString( + mozilla::StaticPrefs::GetPrefName_browser_theme_toolbar_theme())); } } return sInstance; @@ -60,9 +61,10 @@ static void ToolbarThemePrefChanged(const char* aPref, void* aUserInfo); } + (NSSet*)keyPathsForValuesAffectingEffectiveAppearance { - // Automatically notify any key-value observers of our effectiveAppearance property whenever the - // pref or the NSApp's effectiveAppearance change. - return [NSSet setWithObjects:@"toolbarTheme", @"_app.effectiveAppearance", nil]; + // Automatically notify any key-value observers of our effectiveAppearance + // property whenever the pref or the NSApp's effectiveAppearance change. + return + [NSSet setWithObjects:@"toolbarTheme", @"_app.effectiveAppearance", nil]; } - (NSAppearance*)effectiveAppearance { diff --git a/widget/cocoa/DesktopBackgroundImage.mm b/widget/cocoa/DesktopBackgroundImage.mm index 5ebb7ea9380a..7c00109db5e0 100644 --- a/widget/cocoa/DesktopBackgroundImage.mm +++ b/widget/cocoa/DesktopBackgroundImage.mm @@ -52,15 +52,16 @@ void SetDesktopImage(nsIFile* aImage) { } // Use existing options for this screen - NSDictionary* screenOptions = - [[NSWorkspace sharedWorkspace] desktopImageOptionsForScreen:currentScreen]; + NSDictionary* screenOptions = [[NSWorkspace sharedWorkspace] + desktopImageOptionsForScreen:currentScreen]; NSError* error = nil; if (![[NSWorkspace sharedWorkspace] setDesktopImageURL:url forScreen:currentScreen options:screenOptions error:&error]) { - LOG("%s ERROR: setDesktopImageURL failed (%ld)", __func__, (long)[error code]); + LOG("%s ERROR: setDesktopImageURL failed (%ld)", __func__, + (long)[error code]); } } diff --git a/widget/cocoa/GfxInfo.mm b/widget/cocoa/GfxInfo.mm index 19944e9c02f8..ff75a539498a 100644 --- a/widget/cocoa/GfxInfo.mm +++ b/widget/cocoa/GfxInfo.mm @@ -31,7 +31,9 @@ using namespace mozilla::widget; NS_IMPL_ISUPPORTS_INHERITED(GfxInfo, GfxInfoBase, nsIGfxInfoDebug) #endif -GfxInfo::GfxInfo() : mNumGPUsDetected(0), mOSXVersion{0} { mAdapterRAM[0] = mAdapterRAM[1] = 0; } +GfxInfo::GfxInfo() : mNumGPUsDetected(0), mOSXVersion{0} { + mAdapterRAM[0] = mAdapterRAM[1] = 0; +} static OperatingSystem OSXVersionToOperatingSystem(uint32_t aOSXVersion) { switch (nsCocoaFeatures::ExtractMajorVersion(aOSXVersion)) { @@ -78,10 +80,11 @@ static OperatingSystem OSXVersionToOperatingSystem(uint32_t aOSXVersion) { return OperatingSystem::Unknown; } // The following three functions are derived from Chromium code -static CFTypeRef SearchPortForProperty(io_registry_entry_t dspPort, CFStringRef propertyName) { - return IORegistryEntrySearchCFProperty(dspPort, kIOServicePlane, propertyName, - kCFAllocatorDefault, - kIORegistryIterateRecursively | kIORegistryIterateParents); +static CFTypeRef SearchPortForProperty(io_registry_entry_t dspPort, + CFStringRef propertyName) { + return IORegistryEntrySearchCFProperty( + dspPort, kIOServicePlane, propertyName, kCFAllocatorDefault, + kIORegistryIterateRecursively | kIORegistryIterateParents); } static uint32_t IntValueOfCFData(CFDataRef d) { @@ -100,29 +103,33 @@ void GfxInfo::GetDeviceInfo() { CFMutableDictionaryRef pci_dev_dict = IOServiceMatching("IOPCIDevice"); io_iterator_t io_iter; - if (IOServiceGetMatchingServices(kIOMasterPortDefault, pci_dev_dict, &io_iter) != - kIOReturnSuccess) { - MOZ_DIAGNOSTIC_ASSERT(false, - "Failed to detect any GPUs (couldn't enumerate IOPCIDevice services)"); + if (IOServiceGetMatchingServices(kIOMasterPortDefault, pci_dev_dict, + &io_iter) != kIOReturnSuccess) { + MOZ_DIAGNOSTIC_ASSERT( + false, + "Failed to detect any GPUs (couldn't enumerate IOPCIDevice services)"); return; } io_registry_entry_t entry = IO_OBJECT_NULL; while ((entry = IOIteratorNext(io_iter)) != IO_OBJECT_NULL) { constexpr uint32_t kClassCodeDisplayVGA = 0x30000; - CFTypeRef class_code_ref = SearchPortForProperty(entry, CFSTR("class-code")); + CFTypeRef class_code_ref = + SearchPortForProperty(entry, CFSTR("class-code")); if (class_code_ref) { const uint32_t class_code = IntValueOfCFData((CFDataRef)class_code_ref); CFRelease(class_code_ref); if (class_code == kClassCodeDisplayVGA) { - CFTypeRef vendor_id_ref = SearchPortForProperty(entry, CFSTR("vendor-id")); + CFTypeRef vendor_id_ref = + SearchPortForProperty(entry, CFSTR("vendor-id")); if (vendor_id_ref) { mAdapterVendorID[mNumGPUsDetected].AppendPrintf( "0x%04x", IntValueOfCFData((CFDataRef)vendor_id_ref)); CFRelease(vendor_id_ref); } - CFTypeRef device_id_ref = SearchPortForProperty(entry, CFSTR("device-id")); + CFTypeRef device_id_ref = + SearchPortForProperty(entry, CFSTR("device-id")); if (device_id_ref) { mAdapterDeviceID[mNumGPUsDetected].AppendPrintf( "0x%04x", IntValueOfCFData((CFDataRef)device_id_ref)); @@ -145,14 +152,15 @@ void GfxInfo::GetDeviceInfo() { } CFMutableDictionaryRef agx_dev_dict = IOServiceMatching("AGXAccelerator"); - if (IOServiceGetMatchingServices(kIOMasterPortDefault, agx_dev_dict, &io_iter) == - kIOReturnSuccess) { + if (IOServiceGetMatchingServices(kIOMasterPortDefault, agx_dev_dict, + &io_iter) == kIOReturnSuccess) { io_registry_entry_t entry = IO_OBJECT_NULL; while ((entry = IOIteratorNext(io_iter)) != IO_OBJECT_NULL) { - CFTypeRef vendor_id_ref = SearchPortForProperty(entry, CFSTR("vendor-id")); + CFTypeRef vendor_id_ref = + SearchPortForProperty(entry, CFSTR("vendor-id")); if (vendor_id_ref) { - mAdapterVendorID[mNumGPUsDetected].AppendPrintf("0x%04x", - IntValueOfCFData((CFDataRef)vendor_id_ref)); + mAdapterVendorID[mNumGPUsDetected].AppendPrintf( + "0x%04x", IntValueOfCFData((CFDataRef)vendor_id_ref)); CFRelease(vendor_id_ref); ++mNumGPUsDetected; } @@ -189,22 +197,32 @@ NS_IMETHODIMP GfxInfo::GetDWriteEnabled(bool* aEnabled) { return NS_ERROR_FAILURE; } /* readonly attribute bool HasBattery; */ -NS_IMETHODIMP GfxInfo::GetHasBattery(bool* aHasBattery) { return NS_ERROR_NOT_IMPLEMENTED; } +NS_IMETHODIMP GfxInfo::GetHasBattery(bool* aHasBattery) { + return NS_ERROR_NOT_IMPLEMENTED; +} /* readonly attribute DOMString DWriteVersion; */ NS_IMETHODIMP -GfxInfo::GetDWriteVersion(nsAString& aDwriteVersion) { return NS_ERROR_FAILURE; } +GfxInfo::GetDWriteVersion(nsAString& aDwriteVersion) { + return NS_ERROR_FAILURE; +} NS_IMETHODIMP -GfxInfo::GetEmbeddedInFirefoxReality(bool* aEmbeddedInFirefoxReality) { return NS_ERROR_FAILURE; } +GfxInfo::GetEmbeddedInFirefoxReality(bool* aEmbeddedInFirefoxReality) { + return NS_ERROR_FAILURE; +} /* readonly attribute DOMString cleartypeParameters; */ NS_IMETHODIMP -GfxInfo::GetCleartypeParameters(nsAString& aCleartypeParams) { return NS_ERROR_FAILURE; } +GfxInfo::GetCleartypeParameters(nsAString& aCleartypeParams) { + return NS_ERROR_FAILURE; +} /* readonly attribute DOMString windowProtocol; */ NS_IMETHODIMP -GfxInfo::GetWindowProtocol(nsAString& aWindowProtocol) { return NS_ERROR_NOT_IMPLEMENTED; } +GfxInfo::GetWindowProtocol(nsAString& aWindowProtocol) { + return NS_ERROR_NOT_IMPLEMENTED; +} /* readonly attribute DOMString testType; */ NS_IMETHODIMP @@ -348,14 +366,20 @@ GfxInfo::GetAdapterDeviceID2(nsAString& aAdapterDeviceID) { /* readonly attribute DOMString adapterSubsysID; */ NS_IMETHODIMP -GfxInfo::GetAdapterSubsysID(nsAString& aAdapterSubsysID) { return NS_ERROR_FAILURE; } +GfxInfo::GetAdapterSubsysID(nsAString& aAdapterSubsysID) { + return NS_ERROR_FAILURE; +} /* readonly attribute DOMString adapterSubsysID2; */ NS_IMETHODIMP -GfxInfo::GetAdapterSubsysID2(nsAString& aAdapterSubsysID) { return NS_ERROR_FAILURE; } +GfxInfo::GetAdapterSubsysID2(nsAString& aAdapterSubsysID) { + return NS_ERROR_FAILURE; +} NS_IMETHODIMP -GfxInfo::GetDrmRenderDevice(nsACString& aDrmRenderDevice) { return NS_ERROR_NOT_IMPLEMENTED; } +GfxInfo::GetDrmRenderDevice(nsACString& aDrmRenderDevice) { + return NS_ERROR_NOT_IMPLEMENTED; +} /* readonly attribute boolean isGPU2Active; */ NS_IMETHODIMP @@ -372,60 +396,70 @@ void GfxInfo::AddCrashReportAnnotations() { GetAdapterDriverVersion(driverVersion); CopyUTF16toUTF8(driverVersion, narrowDriverVersion); - CrashReporter::AnnotateCrashReport(CrashReporter::Annotation::AdapterVendorID, narrowVendorID); - CrashReporter::AnnotateCrashReport(CrashReporter::Annotation::AdapterDeviceID, narrowDeviceID); - CrashReporter::AnnotateCrashReport(CrashReporter::Annotation::AdapterDriverVersion, - narrowDriverVersion); + CrashReporter::AnnotateCrashReport(CrashReporter::Annotation::AdapterVendorID, + narrowVendorID); + CrashReporter::AnnotateCrashReport(CrashReporter::Annotation::AdapterDeviceID, + narrowDeviceID); + CrashReporter::AnnotateCrashReport( + CrashReporter::Annotation::AdapterDriverVersion, narrowDriverVersion); } // We don't support checking driver versions on Mac. -#define IMPLEMENT_MAC_DRIVER_BLOCKLIST(os, device, features, blockOn, ruleId) \ - APPEND_TO_DRIVER_BLOCKLIST(os, device, features, blockOn, DRIVER_COMPARISON_IGNORED, \ - V(0, 0, 0, 0), ruleId, "") +#define IMPLEMENT_MAC_DRIVER_BLOCKLIST(os, device, features, blockOn, ruleId) \ + APPEND_TO_DRIVER_BLOCKLIST(os, device, features, blockOn, \ + DRIVER_COMPARISON_IGNORED, V(0, 0, 0, 0), ruleId, \ + "") const nsTArray& GfxInfo::GetGfxDriverInfo() { if (!sDriverInfo->Length()) { IMPLEMENT_MAC_DRIVER_BLOCKLIST( - OperatingSystem::OSX, DeviceFamily::RadeonX1000, nsIGfxInfo::FEATURE_OPENGL_LAYERS, - nsIGfxInfo::FEATURE_BLOCKED_DEVICE, "FEATURE_FAILURE_MAC_RADEONX1000_NO_TEXTURE2D"); + OperatingSystem::OSX, DeviceFamily::RadeonX1000, + nsIGfxInfo::FEATURE_OPENGL_LAYERS, nsIGfxInfo::FEATURE_BLOCKED_DEVICE, + "FEATURE_FAILURE_MAC_RADEONX1000_NO_TEXTURE2D"); IMPLEMENT_MAC_DRIVER_BLOCKLIST( - OperatingSystem::OSX, DeviceFamily::Geforce7300GT, nsIGfxInfo::FEATURE_WEBGL_OPENGL, - nsIGfxInfo::FEATURE_BLOCKED_DEVICE, "FEATURE_FAILURE_MAC_7300_NO_WEBGL"); - IMPLEMENT_MAC_DRIVER_BLOCKLIST(OperatingSystem::OSX, DeviceFamily::IntelHDGraphicsToIvyBridge, - nsIGfxInfo::FEATURE_GL_SWIZZLE, - nsIGfxInfo::FEATURE_BLOCKED_DEVICE, - "FEATURE_FAILURE_MAC_INTELHD4000_NO_SWIZZLE"); - // We block texture swizzling everwhere on mac because it's broken in some configurations - // and we want to support GPU switching. + OperatingSystem::OSX, DeviceFamily::Geforce7300GT, + nsIGfxInfo::FEATURE_WEBGL_OPENGL, nsIGfxInfo::FEATURE_BLOCKED_DEVICE, + "FEATURE_FAILURE_MAC_7300_NO_WEBGL"); + IMPLEMENT_MAC_DRIVER_BLOCKLIST( + OperatingSystem::OSX, DeviceFamily::IntelHDGraphicsToIvyBridge, + nsIGfxInfo::FEATURE_GL_SWIZZLE, nsIGfxInfo::FEATURE_BLOCKED_DEVICE, + "FEATURE_FAILURE_MAC_INTELHD4000_NO_SWIZZLE"); + // We block texture swizzling everwhere on mac because it's broken in some + // configurations and we want to support GPU switching. IMPLEMENT_MAC_DRIVER_BLOCKLIST( OperatingSystem::OSX, DeviceFamily::All, nsIGfxInfo::FEATURE_GL_SWIZZLE, - nsIGfxInfo::FEATURE_BLOCKED_DEVICE, "FEATURE_FAILURE_MAC_GPU_SWITCHING_NO_SWIZZLE"); + nsIGfxInfo::FEATURE_BLOCKED_DEVICE, + "FEATURE_FAILURE_MAC_GPU_SWITCHING_NO_SWIZZLE"); // Older generation Intel devices do not perform well with WebRender. IMPLEMENT_MAC_DRIVER_BLOCKLIST( - OperatingSystem::OSX, DeviceFamily::IntelWebRenderBlocked, nsIGfxInfo::FEATURE_WEBRENDER, - nsIGfxInfo::FEATURE_BLOCKED_DEVICE, "FEATURE_FAILURE_INTEL_GEN5_OR_OLDER"); + OperatingSystem::OSX, DeviceFamily::IntelWebRenderBlocked, + nsIGfxInfo::FEATURE_WEBRENDER, nsIGfxInfo::FEATURE_BLOCKED_DEVICE, + "FEATURE_FAILURE_INTEL_GEN5_OR_OLDER"); // Intel HD3000 disabled due to bug 1661505 IMPLEMENT_MAC_DRIVER_BLOCKLIST( - OperatingSystem::OSX, DeviceFamily::IntelSandyBridge, nsIGfxInfo::FEATURE_WEBRENDER, - nsIGfxInfo::FEATURE_BLOCKED_DEVICE, "FEATURE_FAILURE_INTEL_MAC_HD3000_NO_WEBRENDER"); + OperatingSystem::OSX, DeviceFamily::IntelSandyBridge, + nsIGfxInfo::FEATURE_WEBRENDER, nsIGfxInfo::FEATURE_BLOCKED_DEVICE, + "FEATURE_FAILURE_INTEL_MAC_HD3000_NO_WEBRENDER"); // wgpu doesn't safely support OOB behavior on Metal yet. - IMPLEMENT_MAC_DRIVER_BLOCKLIST(OperatingSystem::OSX, DeviceFamily::All, - nsIGfxInfo::FEATURE_WEBGPU, nsIGfxInfo::FEATURE_BLOCKED_DEVICE, - "FEATURE_FAILURE_MAC_WGPU_NO_METAL_BOUNDS_CHECKS"); + IMPLEMENT_MAC_DRIVER_BLOCKLIST( + OperatingSystem::OSX, DeviceFamily::All, nsIGfxInfo::FEATURE_WEBGPU, + nsIGfxInfo::FEATURE_BLOCKED_DEVICE, + "FEATURE_FAILURE_MAC_WGPU_NO_METAL_BOUNDS_CHECKS"); } return *sDriverInfo; } -OperatingSystem GfxInfo::GetOperatingSystem() { return OSXVersionToOperatingSystem(mOSXVersion); } +OperatingSystem GfxInfo::GetOperatingSystem() { + return OSXVersionToOperatingSystem(mOSXVersion); +} -nsresult GfxInfo::GetFeatureStatusImpl(int32_t aFeature, int32_t* aStatus, - nsAString& aSuggestedDriverVersion, - const nsTArray& aDriverInfo, - nsACString& aFailureId, - OperatingSystem* aOS /* = nullptr */) { +nsresult GfxInfo::GetFeatureStatusImpl( + int32_t aFeature, int32_t* aStatus, nsAString& aSuggestedDriverVersion, + const nsTArray& aDriverInfo, nsACString& aFailureId, + OperatingSystem* aOS /* = nullptr */) { NS_ENSURE_ARG_POINTER(aStatus); aSuggestedDriverVersion.SetIsVoid(true); *aStatus = nsIGfxInfo::FEATURE_STATUS_UNKNOWN; @@ -436,7 +470,8 @@ nsresult GfxInfo::GetFeatureStatusImpl(int32_t aFeature, int32_t* aStatus, return NS_OK; } - // Don't evaluate special cases when we're evaluating the downloaded blocklist. + // Don't evaluate special cases when we're evaluating the downloaded + // blocklist. if (!aDriverInfo.Length()) { if (aFeature == nsIGfxInfo::FEATURE_CANVAS2D_ACCELERATION) { // See bug 1249659 @@ -460,8 +495,8 @@ nsresult GfxInfo::GetFeatureStatusImpl(int32_t aFeature, int32_t* aStatus, } } - return GfxInfoBase::GetFeatureStatusImpl(aFeature, aStatus, aSuggestedDriverVersion, aDriverInfo, - aFailureId, &os); + return GfxInfoBase::GetFeatureStatusImpl( + aFeature, aStatus, aSuggestedDriverVersion, aDriverInfo, aFailureId, &os); } #ifdef DEBUG diff --git a/widget/cocoa/MOZIconHelper.mm b/widget/cocoa/MOZIconHelper.mm index 2af89af2ed76..e15407b79761 100644 --- a/widget/cocoa/MOZIconHelper.mm +++ b/widget/cocoa/MOZIconHelper.mm @@ -23,19 +23,20 @@ + (NSImage*)iconImageFromImageContainer:(imgIContainer*)aImage withSize:(NSSize)aSize presContext:(const nsPresContext*)aPresContext - computedStyle:(const mozilla::ComputedStyle*)aComputedStyle + computedStyle: + (const mozilla::ComputedStyle*)aComputedStyle scaleFactor:(CGFloat)aScaleFactor { bool isEntirelyBlack = false; NSImage* retainedImage = nil; nsresult rv; if (aScaleFactor != 0.0f) { - rv = nsCocoaUtils::CreateNSImageFromImageContainer(aImage, imgIContainer::FRAME_CURRENT, - aPresContext, aComputedStyle, &retainedImage, - aScaleFactor, &isEntirelyBlack); + rv = nsCocoaUtils::CreateNSImageFromImageContainer( + aImage, imgIContainer::FRAME_CURRENT, aPresContext, aComputedStyle, + &retainedImage, aScaleFactor, &isEntirelyBlack); } else { rv = nsCocoaUtils::CreateDualRepresentationNSImageFromImageContainer( - aImage, imgIContainer::FRAME_CURRENT, aPresContext, aComputedStyle, &retainedImage, - &isEntirelyBlack); + aImage, imgIContainer::FRAME_CURRENT, aPresContext, aComputedStyle, + &retainedImage, &isEntirelyBlack); } NSImage* image = [retainedImage autorelease]; diff --git a/widget/cocoa/MOZMenuOpeningCoordinator.mm b/widget/cocoa/MOZMenuOpeningCoordinator.mm index 3ac4d8385ffc..41554ab9a92b 100644 --- a/widget/cocoa/MOZMenuOpeningCoordinator.mm +++ b/widget/cocoa/MOZMenuOpeningCoordinator.mm @@ -68,7 +68,8 @@ static BOOL sNeedToUnwindForMenuClosing = NO; withAppearance:(NSAppearance*)aAppearance asContextMenu:(BOOL)aIsContextMenu { MOZ_RELEASE_ASSERT(!mPendingOpening, - "A menu is already waiting to open. Before opening the next one, either wait " + "A menu is already waiting to open. Before opening the " + "next one, either wait " "for this one to open or cancel the request."); NSInteger handle = ++mLastHandle; @@ -134,33 +135,36 @@ static BOOL sNeedToUnwindForMenuClosing = NO; asContextMenu:(BOOL)aIsContextMenu { // There are multiple ways to display an NSMenu as a context menu. // - // 1. We can return the NSMenu from -[ChildView menuForEvent:] and the NSView will open it for - // us. - // 2. We can call +[NSMenu popUpContextMenu:withEvent:forView:] inside a mouseDown handler with a - // real mouse down event. - // 3. We can call +[NSMenu popUpContextMenu:withEvent:forView:] at a later time, with a real - // mouse event that we stored earlier. - // 4. We can call +[NSMenu popUpContextMenu:withEvent:forView:] at any time, with a synthetic - // mouse event that we create just for that purpose. - // 5. We can call -[NSMenu popUpMenuPositioningItem:atLocation:inView:] and it just takes a - // position, not an event. + // 1. We can return the NSMenu from -[ChildView menuForEvent:] and the NSView + // will open it for us. + // 2. We can call +[NSMenu popUpContextMenu:withEvent:forView:] inside a + // mouseDown handler with a real mouse down event. + // 3. We can call +[NSMenu popUpContextMenu:withEvent:forView:] at a later + // time, with a real mouse event that we stored earlier. + // 4. We can call +[NSMenu popUpContextMenu:withEvent:forView:] at any time, + // with a synthetic mouse event that we create just for that purpose. + // 5. We can call -[NSMenu popUpMenuPositioningItem:atLocation:inView:] and + // it just takes a position, not an event. // - // 1-4 look the same, 5 looks different: 5 is made for use with NSPopUpButton, where the selected - // item needs to be shown at a specific position. If a tall menu is opened with a position close - // to the bottom edge of the screen, 5 results in a cropped menu with scroll arrows, even if the - // entire menu would fit on the screen, due to the positioning constraint. - // 1-2 only work if the menu contents are known synchronously during the call to menuForEvent or + // 1-4 look the same, 5 looks different: 5 is made for use with NSPopUpButton, + // where the selected item needs to be shown at a specific position. If a tall + // menu is opened with a position close to the bottom edge of the screen, 5 + // results in a cropped menu with scroll arrows, even if the entire menu would + // fit on the screen, due to the positioning constraint. 1-2 only work if the + // menu contents are known synchronously during the call to menuForEvent or // during the mouseDown event handler. - // NativeMenuMac::ShowAsContextMenu can be called at any time. It could be called during a - // menuForEvent call (during a "contextmenu" event handler), or during a mouseDown handler, or at - // a later time. - // The code below uses option 4 as the preferred option for context menus because it's the - // simplest: It works in all scenarios and it doesn't have the drawbacks of option 5. For popups - // that aren't context menus and that should be positioned as close as possible to the given - // screen position, we use option 5. + // NativeMenuMac::ShowAsContextMenu can be called at any time. It could be + // called during a menuForEvent call (during a "contextmenu" event handler), + // or during a mouseDown handler, or at a later time. The code below uses + // option 4 as the preferred option for context menus because it's the + // simplest: It works in all scenarios and it doesn't have the drawbacks of + // option 5. For popups that aren't context menus and that should be + // positioned as close as possible to the given screen position, we use + // option 5. if (aAppearance) { -#if !defined(MAC_OS_VERSION_11_0) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_VERSION_11_0 +#if !defined(MAC_OS_VERSION_11_0) || \ + MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_VERSION_11_0 if (nsCocoaFeatures::OnBigSurOrLater()) { #else if (@available(macOS 11.0, *)) { @@ -174,18 +178,21 @@ static BOOL sNeedToUnwindForMenuClosing = NO; if (aView) { NSWindow* window = aView.window; - NSPoint locationInWindow = nsCocoaUtils::ConvertPointFromScreen(window, aPosition); + NSPoint locationInWindow = + nsCocoaUtils::ConvertPointFromScreen(window, aPosition); if (aIsContextMenu) { - // Create a synthetic event at the right location and open the menu [option 4]. - NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeRightMouseDown - location:locationInWindow - modifierFlags:0 - timestamp:NSProcessInfo.processInfo.systemUptime - windowNumber:window.windowNumber - context:nil - eventNumber:0 - clickCount:1 - pressure:0.0f]; + // Create a synthetic event at the right location and open the menu + // [option 4]. + NSEvent* event = + [NSEvent mouseEventWithType:NSEventTypeRightMouseDown + location:locationInWindow + modifierFlags:0 + timestamp:NSProcessInfo.processInfo.systemUptime + windowNumber:window.windowNumber + context:nil + eventNumber:0 + clickCount:1 + pressure:0.0f]; [NSMenu popUpContextMenu:aMenu withEvent:event forView:aView]; } else { // For popups which are not context menus, we open the menu using [option @@ -193,14 +200,18 @@ static BOOL sNeedToUnwindForMenuClosing = NO; // corner of the menu. This path is used for anchored menupopups, so we // prefer option 5 over option 4 so that the menu doesn't get flipped if // space is tight. - NSPoint locationInView = [aView convertPoint:locationInWindow fromView:nil]; - [aMenu popUpMenuPositioningItem:nil atLocation:locationInView inView:aView]; + NSPoint locationInView = [aView convertPoint:locationInWindow + fromView:nil]; + [aMenu popUpMenuPositioningItem:nil + atLocation:locationInView + inView:aView]; } } else { - // Open the menu using popUpMenuPositioningItem:atLocation:inView: [option 5]. - // This is not preferred, because it positions the menu differently from how a native context - // menu would be positioned; it enforces aPosition for the top left corner even if this - // means that the menu will be displayed in a clipped fashion with scroll arrows. + // Open the menu using popUpMenuPositioningItem:atLocation:inView: [option + // 5]. This is not preferred, because it positions the menu differently from + // how a native context menu would be positioned; it enforces aPosition for + // the top left corner even if this means that the menu will be displayed in + // a clipped fashion with scroll arrows. [aMenu popUpMenuPositioningItem:nil atLocation:aPosition inView:nil]; } } diff --git a/widget/cocoa/MediaHardwareKeysEventSourceMac.mm b/widget/cocoa/MediaHardwareKeysEventSourceMac.mm index 669410018b77..9a6991a181c2 100644 --- a/widget/cocoa/MediaHardwareKeysEventSourceMac.mm +++ b/widget/cocoa/MediaHardwareKeysEventSourceMac.mm @@ -70,7 +70,9 @@ static MediaControlKey ToMediaControlKey(int aKeyCode) { namespace mozilla { namespace widget { -bool MediaHardwareKeysEventSourceMac::IsOpened() const { return mEventTap && mEventTapSource; } +bool MediaHardwareKeysEventSourceMac::IsOpened() const { + return mEventTap && mEventTapSource; +} bool MediaHardwareKeysEventSourceMac::Open() { LOG("Open MediaHardwareKeysEventSourceMac"); @@ -89,22 +91,24 @@ bool MediaHardwareKeysEventSourceMac::StartEventTap() { MOZ_ASSERT(!mEventTapSource); // Add an event tap to intercept the system defined media key events. - mEventTap = - CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionListenOnly, - CGEventMaskBit(NX_SYSDEFINED), EventTapCallback, this); + mEventTap = CGEventTapCreate( + kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionListenOnly, + CGEventMaskBit(NX_SYSDEFINED), EventTapCallback, this); if (!mEventTap) { LOG("Fail to create event tap"); return false; } - mEventTapSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, mEventTap, 0); + mEventTapSource = + CFMachPortCreateRunLoopSource(kCFAllocatorDefault, mEventTap, 0); if (!mEventTapSource) { LOG("Fail to create an event tap source."); return false; } LOG("Add an event tap source to current loop"); - CFRunLoopAddSource(CFRunLoopGetCurrent(), mEventTapSource, kCFRunLoopCommonModes); + CFRunLoopAddSource(CFRunLoopGetCurrent(), mEventTapSource, + kCFRunLoopCommonModes); return true; } @@ -115,18 +119,20 @@ void MediaHardwareKeysEventSourceMac::StopEventTap() { mEventTap = nullptr; } if (mEventTapSource) { - CFRunLoopRemoveSource(CFRunLoopGetCurrent(), mEventTapSource, kCFRunLoopCommonModes); + CFRunLoopRemoveSource(CFRunLoopGetCurrent(), mEventTapSource, + kCFRunLoopCommonModes); CFRelease(mEventTapSource); mEventTapSource = nullptr; } } -CGEventRef MediaHardwareKeysEventSourceMac::EventTapCallback(CGEventTapProxy proxy, - CGEventType type, CGEventRef event, - void* refcon) { +CGEventRef MediaHardwareKeysEventSourceMac::EventTapCallback( + CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) { // Re-enable event tap when receiving disabled events. - MediaHardwareKeysEventSourceMac* source = static_cast(refcon); - if (type == kCGEventTapDisabledByUserInput || type == kCGEventTapDisabledByTimeout) { + MediaHardwareKeysEventSourceMac* source = + static_cast(refcon); + if (type == kCGEventTapDisabledByUserInput || + type == kCGEventTapDisabledByTimeout) { MOZ_ASSERT(source->mEventTap); CGEventTapEnable(source->mEventTap, true); return event; @@ -151,8 +157,9 @@ CGEventRef MediaHardwareKeysEventSourceMac::EventTapCallback(CGEventTapProxy pro // - keyRepeat = (keyFlags & 0x1); const NSInteger data1 = [nsEvent data1]; int keyCode = (data1 & 0xFFFF0000) >> 16; - if (keyCode != NX_KEYTYPE_PLAY && keyCode != NX_KEYTYPE_NEXT && keyCode != NX_KEYTYPE_PREVIOUS && - keyCode != NX_KEYTYPE_FAST && keyCode != NX_KEYTYPE_REWIND) { + if (keyCode != NX_KEYTYPE_PLAY && keyCode != NX_KEYTYPE_NEXT && + keyCode != NX_KEYTYPE_PREVIOUS && keyCode != NX_KEYTYPE_FAST && + keyCode != NX_KEYTYPE_REWIND) { return event; } @@ -173,7 +180,8 @@ CGEventRef MediaHardwareKeysEventSourceMac::EventTapCallback(CGEventTapProxy pro } LOG2("Get media key %s", source, ToMediaControlKeyStr(keyCode)); - for (auto iter = source->mListeners.begin(); iter != source->mListeners.end(); ++iter) { + for (auto iter = source->mListeners.begin(); iter != source->mListeners.end(); + ++iter) { (*iter)->OnActionPerformed(MediaControlAction(ToMediaControlKey(keyCode))); } return event; diff --git a/widget/cocoa/MediaHardwareKeysEventSourceMacMediaCenter.mm b/widget/cocoa/MediaHardwareKeysEventSourceMacMediaCenter.mm index 9637c11d81f7..c7a85326fbb4 100644 --- a/widget/cocoa/MediaHardwareKeysEventSourceMacMediaCenter.mm +++ b/widget/cocoa/MediaHardwareKeysEventSourceMacMediaCenter.mm @@ -13,39 +13,45 @@ using namespace mozilla::dom; // avoid redefined macro in unified build #undef LOG -#define LOG(msg, ...) \ - MOZ_LOG(gMediaControlLog, LogLevel::Debug, \ - ("MediaHardwareKeysEventSourceMacMediaCenter=%p, " msg, this, ##__VA_ARGS__)) +#define LOG(msg, ...) \ + MOZ_LOG(gMediaControlLog, LogLevel::Debug, \ + ("MediaHardwareKeysEventSourceMacMediaCenter=%p, " msg, this, \ + ##__VA_ARGS__)) namespace mozilla { namespace widget { -MediaCenterEventHandler MediaHardwareKeysEventSourceMacMediaCenter::CreatePlayPauseHandler() { +MediaCenterEventHandler +MediaHardwareKeysEventSourceMacMediaCenter::CreatePlayPauseHandler() { return Block_copy(^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent* event) { MPNowPlayingInfoCenter* center = [MPNowPlayingInfoCenter defaultCenter]; - center.playbackState = center.playbackState == MPNowPlayingPlaybackStatePlaying - ? MPNowPlayingPlaybackStatePaused - : MPNowPlayingPlaybackStatePlaying; + center.playbackState = + center.playbackState == MPNowPlayingPlaybackStatePlaying + ? MPNowPlayingPlaybackStatePaused + : MPNowPlayingPlaybackStatePlaying; HandleEvent(MediaControlKey::Playpause); return MPRemoteCommandHandlerStatusSuccess; }); } -MediaCenterEventHandler MediaHardwareKeysEventSourceMacMediaCenter::CreateNextTrackHandler() { +MediaCenterEventHandler +MediaHardwareKeysEventSourceMacMediaCenter::CreateNextTrackHandler() { return Block_copy(^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent* event) { HandleEvent(MediaControlKey::Nexttrack); return MPRemoteCommandHandlerStatusSuccess; }); } -MediaCenterEventHandler MediaHardwareKeysEventSourceMacMediaCenter::CreatePreviousTrackHandler() { +MediaCenterEventHandler +MediaHardwareKeysEventSourceMacMediaCenter::CreatePreviousTrackHandler() { return Block_copy(^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent* event) { HandleEvent(MediaControlKey::Previoustrack); return MPRemoteCommandHandlerStatusSuccess; }); } -MediaCenterEventHandler MediaHardwareKeysEventSourceMacMediaCenter::CreatePlayHandler() { +MediaCenterEventHandler +MediaHardwareKeysEventSourceMacMediaCenter::CreatePlayHandler() { return Block_copy(^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent* event) { MPNowPlayingInfoCenter* center = [MPNowPlayingInfoCenter defaultCenter]; if (center.playbackState != MPNowPlayingPlaybackStatePlaying) { @@ -56,7 +62,8 @@ MediaCenterEventHandler MediaHardwareKeysEventSourceMacMediaCenter::CreatePlayHa }); } -MediaCenterEventHandler MediaHardwareKeysEventSourceMacMediaCenter::CreatePauseHandler() { +MediaCenterEventHandler +MediaHardwareKeysEventSourceMacMediaCenter::CreatePauseHandler() { return Block_copy(^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent* event) { MPNowPlayingInfoCenter* center = [MPNowPlayingInfoCenter defaultCenter]; if (center.playbackState != MPNowPlayingPlaybackStatePaused) { @@ -67,7 +74,8 @@ MediaCenterEventHandler MediaHardwareKeysEventSourceMacMediaCenter::CreatePauseH }); } -MediaHardwareKeysEventSourceMacMediaCenter::MediaHardwareKeysEventSourceMacMediaCenter() { +MediaHardwareKeysEventSourceMacMediaCenter:: + MediaHardwareKeysEventSourceMacMediaCenter() { mPlayPauseHandler = CreatePlayPauseHandler(); mNextTrackHandler = CreateNextTrackHandler(); mPreviousTrackHandler = CreatePreviousTrackHandler(); @@ -76,7 +84,8 @@ MediaHardwareKeysEventSourceMacMediaCenter::MediaHardwareKeysEventSourceMacMedia LOG("Create MediaHardwareKeysEventSourceMacMediaCenter"); } -MediaHardwareKeysEventSourceMacMediaCenter::~MediaHardwareKeysEventSourceMacMediaCenter() { +MediaHardwareKeysEventSourceMacMediaCenter:: + ~MediaHardwareKeysEventSourceMacMediaCenter() { LOG("Destroy MediaHardwareKeysEventSourceMacMediaCenter"); EndListeningForEvents(); MPNowPlayingInfoCenter* center = [MPNowPlayingInfoCenter defaultCenter]; @@ -86,13 +95,15 @@ MediaHardwareKeysEventSourceMacMediaCenter::~MediaHardwareKeysEventSourceMacMedi void MediaHardwareKeysEventSourceMacMediaCenter::BeginListeningForEvents() { MPNowPlayingInfoCenter* center = [MPNowPlayingInfoCenter defaultCenter]; center.playbackState = MPNowPlayingPlaybackStatePlaying; - MPRemoteCommandCenter* commandCenter = [MPRemoteCommandCenter sharedCommandCenter]; + MPRemoteCommandCenter* commandCenter = + [MPRemoteCommandCenter sharedCommandCenter]; commandCenter.togglePlayPauseCommand.enabled = true; [commandCenter.togglePlayPauseCommand addTargetWithHandler:mPlayPauseHandler]; commandCenter.nextTrackCommand.enabled = true; [commandCenter.nextTrackCommand addTargetWithHandler:mNextTrackHandler]; commandCenter.previousTrackCommand.enabled = true; - [commandCenter.previousTrackCommand addTargetWithHandler:mPreviousTrackHandler]; + [commandCenter.previousTrackCommand + addTargetWithHandler:mPreviousTrackHandler]; commandCenter.playCommand.enabled = true; [commandCenter.playCommand addTargetWithHandler:mPlayHandler]; commandCenter.pauseCommand.enabled = true; @@ -103,7 +114,8 @@ void MediaHardwareKeysEventSourceMacMediaCenter::EndListeningForEvents() { MPNowPlayingInfoCenter* center = [MPNowPlayingInfoCenter defaultCenter]; center.playbackState = MPNowPlayingPlaybackStatePaused; center.nowPlayingInfo = nil; - MPRemoteCommandCenter* commandCenter = [MPRemoteCommandCenter sharedCommandCenter]; + MPRemoteCommandCenter* commandCenter = + [MPRemoteCommandCenter sharedCommandCenter]; commandCenter.togglePlayPauseCommand.enabled = false; [commandCenter.togglePlayPauseCommand removeTarget:nil]; commandCenter.nextTrackCommand.enabled = false; @@ -131,9 +143,12 @@ void MediaHardwareKeysEventSourceMacMediaCenter::Close() { MediaControlKeySource::Close(); } -bool MediaHardwareKeysEventSourceMacMediaCenter::IsOpened() const { return mOpened; } +bool MediaHardwareKeysEventSourceMacMediaCenter::IsOpened() const { + return mOpened; +} -void MediaHardwareKeysEventSourceMacMediaCenter::HandleEvent(MediaControlKey aEvent) { +void MediaHardwareKeysEventSourceMacMediaCenter::HandleEvent( + MediaControlKey aEvent) { for (auto iter = mListeners.begin(); iter != mListeners.end(); ++iter) { (*iter)->OnActionPerformed(MediaControlAction(aEvent)); } diff --git a/widget/cocoa/NativeKeyBindings.mm b/widget/cocoa/NativeKeyBindings.mm index d3e598325905..e4bdf715e2fb 100644 --- a/widget/cocoa/NativeKeyBindings.mm +++ b/widget/cocoa/NativeKeyBindings.mm @@ -56,12 +56,16 @@ void NativeKeyBindings::Shutdown() { NativeKeyBindings::NativeKeyBindings() {} -inline objc_selector* ToObjcSelectorPtr(SEL aSel) { return reinterpret_cast(aSel); } -#define SEL_TO_COMMAND(aSel, aCommand) \ - mSelectorToCommand.InsertOrUpdate(ToObjcSelectorPtr(@selector(aSel)), aCommand) +inline objc_selector* ToObjcSelectorPtr(SEL aSel) { + return reinterpret_cast(aSel); +} +#define SEL_TO_COMMAND(aSel, aCommand) \ + mSelectorToCommand.InsertOrUpdate(ToObjcSelectorPtr(@selector(aSel)), \ + aCommand) void NativeKeyBindings::Init(NativeKeyBindingsType aType) { - MOZ_LOG(gNativeKeyBindingsLog, LogLevel::Info, ("%p NativeKeyBindings::Init", this)); + MOZ_LOG(gNativeKeyBindingsLog, LogLevel::Info, + ("%p NativeKeyBindings::Init", this)); // Many selectors have a one-to-one mapping to a Gecko command. Those mappings // are registered in mSelectorToCommand. @@ -88,7 +92,8 @@ void NativeKeyBindings::Init(NativeKeyBindingsType aType) { // TODO: deleteTo* selectors are also supposed to add text to a kill buffer SEL_TO_COMMAND(deleteToBeginningOfLine:, Command::DeleteToBeginningOfLine); - SEL_TO_COMMAND(deleteToBeginningOfParagraph:, Command::DeleteToBeginningOfLine); + SEL_TO_COMMAND(deleteToBeginningOfParagraph:, + Command::DeleteToBeginningOfLine); SEL_TO_COMMAND(deleteToEndOfLine:, Command::DeleteToEndOfLine); SEL_TO_COMMAND(deleteToEndOfParagraph:, Command::DeleteToEndOfLine); // SEL_TO_COMMAND(deleteToMark:, ); @@ -119,26 +124,34 @@ void NativeKeyBindings::Init(NativeKeyBindingsType aType) { SEL_TO_COMMAND(moveForwardAndModifySelection:, Command::SelectCharNext); SEL_TO_COMMAND(moveLeft:, Command::CharPrevious); SEL_TO_COMMAND(moveLeftAndModifySelection:, Command::SelectCharPrevious); - SEL_TO_COMMAND(moveParagraphBackwardAndModifySelection:, Command::SelectBeginLine); - SEL_TO_COMMAND(moveParagraphForwardAndModifySelection:, Command::SelectEndLine); + SEL_TO_COMMAND(moveParagraphBackwardAndModifySelection:, + Command::SelectBeginLine); + SEL_TO_COMMAND(moveParagraphForwardAndModifySelection:, + Command::SelectEndLine); SEL_TO_COMMAND(moveRight:, Command::CharNext); SEL_TO_COMMAND(moveRightAndModifySelection:, Command::SelectCharNext); SEL_TO_COMMAND(moveToBeginningOfDocument:, Command::MoveTop); - SEL_TO_COMMAND(moveToBeginningOfDocumentAndModifySelection:, Command::SelectTop); + SEL_TO_COMMAND(moveToBeginningOfDocumentAndModifySelection:, + Command::SelectTop); SEL_TO_COMMAND(moveToBeginningOfLine:, Command::BeginLine); - SEL_TO_COMMAND(moveToBeginningOfLineAndModifySelection:, Command::SelectBeginLine); + SEL_TO_COMMAND(moveToBeginningOfLineAndModifySelection:, + Command::SelectBeginLine); SEL_TO_COMMAND(moveToBeginningOfParagraph:, Command::BeginLine); - SEL_TO_COMMAND(moveToBeginningOfParagraphAndModifySelection:, Command::SelectBeginLine); + SEL_TO_COMMAND(moveToBeginningOfParagraphAndModifySelection:, + Command::SelectBeginLine); SEL_TO_COMMAND(moveToEndOfDocument:, Command::MoveBottom); SEL_TO_COMMAND(moveToEndOfDocumentAndModifySelection:, Command::SelectBottom); SEL_TO_COMMAND(moveToEndOfLine:, Command::EndLine); SEL_TO_COMMAND(moveToEndOfLineAndModifySelection:, Command::SelectEndLine); SEL_TO_COMMAND(moveToEndOfParagraph:, Command::EndLine); - SEL_TO_COMMAND(moveToEndOfParagraphAndModifySelection:, Command::SelectEndLine); + SEL_TO_COMMAND(moveToEndOfParagraphAndModifySelection:, + Command::SelectEndLine); SEL_TO_COMMAND(moveToLeftEndOfLine:, Command::BeginLine); - SEL_TO_COMMAND(moveToLeftEndOfLineAndModifySelection:, Command::SelectBeginLine); + SEL_TO_COMMAND(moveToLeftEndOfLineAndModifySelection:, + Command::SelectBeginLine); SEL_TO_COMMAND(moveToRightEndOfLine:, Command::EndLine); - SEL_TO_COMMAND(moveToRightEndOfLineAndModifySelection:, Command::SelectEndLine); + SEL_TO_COMMAND(moveToRightEndOfLineAndModifySelection:, + Command::SelectEndLine); if (aType == NativeKeyBindingsType::SingleLineEditor) { SEL_TO_COMMAND(moveUp:, Command::BeginLine); } else { @@ -146,7 +159,8 @@ void NativeKeyBindings::Init(NativeKeyBindingsType aType) { } SEL_TO_COMMAND(moveUpAndModifySelection:, Command::SelectLinePrevious); SEL_TO_COMMAND(moveWordBackward:, Command::WordPrevious); - SEL_TO_COMMAND(moveWordBackwardAndModifySelection:, Command::SelectWordPrevious); + SEL_TO_COMMAND(moveWordBackwardAndModifySelection:, + Command::SelectWordPrevious); SEL_TO_COMMAND(moveWordForward:, Command::WordNext); SEL_TO_COMMAND(moveWordForwardAndModifySelection:, Command::SelectWordNext); SEL_TO_COMMAND(moveWordLeft:, Command::WordPrevious); @@ -191,7 +205,8 @@ void NativeKeyBindings::GetEditCommands(const WidgetKeyboardEvent& aEvent, MOZ_ASSERT(!aEvent.mFlags.mIsSynthesizedForTests); MOZ_ASSERT(aCommands.IsEmpty()); - MOZ_LOG(gNativeKeyBindingsLog, LogLevel::Info, ("%p NativeKeyBindings::GetEditCommands", this)); + MOZ_LOG(gNativeKeyBindingsLog, LogLevel::Info, + ("%p NativeKeyBindings::GetEditCommands", this)); // Recover the current event, which should always be the key down we are // responding to. @@ -200,7 +215,8 @@ void NativeKeyBindings::GetEditCommands(const WidgetKeyboardEvent& aEvent, if (!cocoaEvent || [cocoaEvent type] != NSEventTypeKeyDown) { MOZ_LOG(gNativeKeyBindingsLog, LogLevel::Info, - ("%p NativeKeyBindings::GetEditCommands, no Cocoa key down event", this)); + ("%p NativeKeyBindings::GetEditCommands, no Cocoa key down event", + this)); return; } @@ -210,7 +226,8 @@ void NativeKeyBindings::GetEditCommands(const WidgetKeyboardEvent& aEvent, NSEvent* originalEvent = cocoaEvent; // TODO: Use KeyNameIndex rather than legacy keyCode. - uint32_t remappedGeckoKeyCode = aEvent.GetRemappedKeyCode(aWritingMode.ref()); + uint32_t remappedGeckoKeyCode = + aEvent.GetRemappedKeyCode(aWritingMode.ref()); uint32_t remappedCocoaKeyCode = 0; switch (remappedGeckoKeyCode) { case NS_VK_UP: @@ -229,8 +246,10 @@ void NativeKeyBindings::GetEditCommands(const WidgetKeyboardEvent& aEvent, MOZ_ASSERT_UNREACHABLE("Add a case for the new remapped key"); return; } - unichar ch = nsCocoaUtils::ConvertGeckoKeyCodeToMacCharCode(remappedGeckoKeyCode); - NSString* chars = [[[NSString alloc] initWithCharacters:&ch length:1] autorelease]; + unichar ch = + nsCocoaUtils::ConvertGeckoKeyCodeToMacCharCode(remappedGeckoKeyCode); + NSString* chars = [[[NSString alloc] initWithCharacters:&ch + length:1] autorelease]; cocoaEvent = [NSEvent keyEventWithType:[originalEvent type] location:[originalEvent locationInWindow] modifierFlags:[originalEvent modifierFlags] @@ -272,11 +291,12 @@ void NativeKeyBindings::GetEditCommands(const WidgetKeyboardEvent& aEvent, LogEditCommands(aCommands, "NativeKeyBindings::GetEditCommands"); } -void NativeKeyBindings::AppendEditCommandsForSelector(objc_selector* aSelector, - nsTArray& aCommands) const { +void NativeKeyBindings::AppendEditCommandsForSelector( + objc_selector* aSelector, nsTArray& aCommands) const { // Try to find a simple mapping in the hashtable Command geckoCommand = Command::DoNothing; - if (mSelectorToCommand.Get(aSelector, &geckoCommand) && geckoCommand != Command::DoNothing) { + if (mSelectorToCommand.Get(aSelector, &geckoCommand) && + geckoCommand != Command::DoNothing) { aCommands.AppendElement(static_cast(geckoCommand)); } else if (aSelector == ToObjcSelectorPtr(@selector(selectLine:))) { // This is functional, but Cocoa's version is direction-less in that @@ -300,7 +320,8 @@ void NativeKeyBindings::LogEditCommands(const nsTArray& aCommands, } if (aCommands.IsEmpty()) { - MOZ_LOG(gNativeKeyBindingsLog, LogLevel::Info, ("%p %s, no edit commands", this, aDescription)); + MOZ_LOG(gNativeKeyBindingsLog, LogLevel::Info, + ("%p %s, no edit commands", this, aDescription)); return; } @@ -313,10 +334,9 @@ void NativeKeyBindings::LogEditCommands(const nsTArray& aCommands, } // static -void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, - const WidgetKeyboardEvent& aEvent, - const Maybe& aWritingMode, - nsTArray& aCommands) { +void NativeKeyBindings::GetEditCommandsForTests( + NativeKeyBindingsType aType, const WidgetKeyboardEvent& aEvent, + const Maybe& aWritingMode, nsTArray& aCommands) { MOZ_DIAGNOSTIC_ASSERT(aEvent.IsTrusted()); // The following mapping is checked on Big Sur. Some of them are defined in: @@ -325,8 +345,9 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, if (NS_WARN_IF(!instance)) { return; } - switch (aWritingMode.isSome() ? aEvent.GetRemappedKeyNameIndex(aWritingMode.ref()) - : aEvent.mKeyNameIndex) { + switch (aWritingMode.isSome() + ? aEvent.GetRemappedKeyNameIndex(aWritingMode.ref()) + : aEvent.mKeyNameIndex) { case KEY_NAME_INDEX_USE_STRING: if (!aEvent.IsControl() || aEvent.IsAlt() || aEvent.IsMeta()) { break; @@ -337,21 +358,23 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, instance->AppendEditCommandsForSelector( !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveToBeginningOfParagraph:)) - : ToObjcSelectorPtr(@selector(moveToBeginningOfParagraphAndModifySelection:)), + : ToObjcSelectorPtr(@selector( + moveToBeginningOfParagraphAndModifySelection:)), aCommands); break; case 'b': case 'B': instance->AppendEditCommandsForSelector( !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveBackward:)) - : ToObjcSelectorPtr(@selector(moveBackwardAndModifySelection:)), + : ToObjcSelectorPtr(@selector( + moveBackwardAndModifySelection:)), aCommands); break; case 'd': case 'D': if (!aEvent.IsShift()) { - instance->AppendEditCommandsForSelector(ToObjcSelectorPtr(@selector(deleteForward:)), - aCommands); + instance->AppendEditCommandsForSelector( + ToObjcSelectorPtr(@selector(deleteForward:)), aCommands); } break; case 'e': @@ -359,42 +382,47 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, instance->AppendEditCommandsForSelector( !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveToEndOfParagraph:)) - : ToObjcSelectorPtr(@selector(moveToEndOfParagraphAndModifySelection:)), + : ToObjcSelectorPtr( + @selector(moveToEndOfParagraphAndModifySelection:)), aCommands); break; case 'f': case 'F': instance->AppendEditCommandsForSelector( !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveForward:)) - : ToObjcSelectorPtr(@selector(moveForwardAndModifySelection:)), + : ToObjcSelectorPtr(@selector( + moveForwardAndModifySelection:)), aCommands); break; case 'h': case 'H': if (!aEvent.IsShift()) { - instance->AppendEditCommandsForSelector(ToObjcSelectorPtr(@selector(deleteBackward:)), - aCommands); + instance->AppendEditCommandsForSelector( + ToObjcSelectorPtr(@selector(deleteBackward:)), aCommands); } break; case 'k': case 'K': if (!aEvent.IsShift()) { instance->AppendEditCommandsForSelector( - ToObjcSelectorPtr(@selector(deleteToEndOfParagraph:)), aCommands); + ToObjcSelectorPtr(@selector(deleteToEndOfParagraph:)), + aCommands); } break; case 'n': case 'N': instance->AppendEditCommandsForSelector( - !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveDown:)) - : ToObjcSelectorPtr(@selector(moveDownAndModifySelection:)), + !aEvent.IsShift() + ? ToObjcSelectorPtr(@selector(moveDown:)) + : ToObjcSelectorPtr(@selector(moveDownAndModifySelection:)), aCommands); break; case 'p': case 'P': instance->AppendEditCommandsForSelector( - !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveUp:)) - : ToObjcSelectorPtr(@selector(moveUpAndModifySelection:)), + !aEvent.IsShift() + ? ToObjcSelectorPtr(@selector(moveUp:)) + : ToObjcSelectorPtr(@selector(moveUpAndModifySelection:)), aCommands); break; default: @@ -413,21 +441,22 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, } if (aEvent.IsAlt()) { // Shift and Control are ignored. - instance->AppendEditCommandsForSelector(ToObjcSelectorPtr(@selector(deleteWordBackward:)), - aCommands); + instance->AppendEditCommandsForSelector( + ToObjcSelectorPtr(@selector(deleteWordBackward:)), aCommands); break; } if (aEvent.IsControl()) { if (aEvent.IsShift()) { instance->AppendEditCommandsForSelector( - ToObjcSelectorPtr(@selector(deleteBackwardByDecomposingPreviousCharacter:)), + ToObjcSelectorPtr( + @selector(deleteBackwardByDecomposingPreviousCharacter:)), aCommands); } break; } // Shift is ignored. - instance->AppendEditCommandsForSelector(ToObjcSelectorPtr(@selector(deleteBackward:)), - aCommands); + instance->AppendEditCommandsForSelector( + ToObjcSelectorPtr(@selector(deleteBackward:)), aCommands); break; case KEY_NAME_INDEX_Delete: if (aEvent.IsControl() || aEvent.IsMeta()) { @@ -435,13 +464,13 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, } if (aEvent.IsAlt()) { // Shift is ignored. - instance->AppendEditCommandsForSelector(ToObjcSelectorPtr(@selector(deleteWordForward:)), - aCommands); + instance->AppendEditCommandsForSelector( + ToObjcSelectorPtr(@selector(deleteWordForward:)), aCommands); break; } // Shift is ignored. - instance->AppendEditCommandsForSelector(ToObjcSelectorPtr(@selector(deleteForward:)), - aCommands); + instance->AppendEditCommandsForSelector( + ToObjcSelectorPtr(@selector(deleteForward:)), aCommands); break; case KEY_NAME_INDEX_PageDown: if (aEvent.IsControl() || aEvent.IsMeta()) { @@ -449,12 +478,14 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, } if (aEvent.IsAlt()) { // Shift is ignored. - instance->AppendEditCommandsForSelector(ToObjcSelectorPtr(@selector(pageDown:)), aCommands); + instance->AppendEditCommandsForSelector( + ToObjcSelectorPtr(@selector(pageDown:)), aCommands); break; } instance->AppendEditCommandsForSelector( - !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(scrollPageDown:)) - : ToObjcSelectorPtr(@selector(pageDownAndModifySelection:)), + !aEvent.IsShift() + ? ToObjcSelectorPtr(@selector(scrollPageDown:)) + : ToObjcSelectorPtr(@selector(pageDownAndModifySelection:)), aCommands); break; case KEY_NAME_INDEX_PageUp: @@ -463,12 +494,14 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, } if (aEvent.IsAlt()) { // Shift is ignored. - instance->AppendEditCommandsForSelector(ToObjcSelectorPtr(@selector(pageUp:)), aCommands); + instance->AppendEditCommandsForSelector( + ToObjcSelectorPtr(@selector(pageUp:)), aCommands); break; } instance->AppendEditCommandsForSelector( - !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(scrollPageUp:)) - : ToObjcSelectorPtr(@selector(pageUpAndModifySelection:)), + !aEvent.IsShift() + ? ToObjcSelectorPtr(@selector(scrollPageUp:)) + : ToObjcSelectorPtr(@selector(pageUpAndModifySelection:)), aCommands); break; case KEY_NAME_INDEX_Home: @@ -478,7 +511,8 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, instance->AppendEditCommandsForSelector( !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(scrollToBeginningOfDocument:)) - : ToObjcSelectorPtr(@selector(moveToBeginningOfDocumentAndModifySelection:)), + : ToObjcSelectorPtr( + @selector(moveToBeginningOfDocumentAndModifySelection:)), aCommands); break; case KEY_NAME_INDEX_End: @@ -486,8 +520,10 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, break; } instance->AppendEditCommandsForSelector( - !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(scrollToEndOfDocument:)) - : ToObjcSelectorPtr(@selector(moveToEndOfDocumentAndModifySelection:)), + !aEvent.IsShift() + ? ToObjcSelectorPtr(@selector(scrollToEndOfDocument:)) + : ToObjcSelectorPtr(@selector + (moveToEndOfDocumentAndModifySelection:)), aCommands); break; case KEY_NAME_INDEX_ArrowLeft: @@ -498,7 +534,8 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, instance->AppendEditCommandsForSelector( !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveToLeftEndOfLine:)) - : ToObjcSelectorPtr(@selector(moveToLeftEndOfLineAndModifySelection:)), + : ToObjcSelectorPtr(@selector + (moveToLeftEndOfLineAndModifySelection:)), aCommands); break; } @@ -506,8 +543,9 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, break; } instance->AppendEditCommandsForSelector( - !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveLeft:)) - : ToObjcSelectorPtr(@selector(moveLeftAndModifySelection:)), + !aEvent.IsShift() + ? ToObjcSelectorPtr(@selector(moveLeft:)) + : ToObjcSelectorPtr(@selector(moveLeftAndModifySelection:)), aCommands); break; case KEY_NAME_INDEX_ArrowRight: @@ -518,7 +556,8 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, instance->AppendEditCommandsForSelector( !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveToRightEndOfLine:)) - : ToObjcSelectorPtr(@selector(moveToRightEndOfLineAndModifySelection:)), + : ToObjcSelectorPtr(@selector + (moveToRightEndOfLineAndModifySelection:)), aCommands); break; } @@ -526,8 +565,9 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, break; } instance->AppendEditCommandsForSelector( - !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveRight:)) - : ToObjcSelectorPtr(@selector(moveRightAndModifySelection:)), + !aEvent.IsShift() + ? ToObjcSelectorPtr(@selector(moveRight:)) + : ToObjcSelectorPtr(@selector(moveRightAndModifySelection:)), aCommands); break; case KEY_NAME_INDEX_ArrowUp: @@ -541,25 +581,30 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, instance->AppendEditCommandsForSelector( !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveToBeginningOfDocument:)) - : ToObjcSelectorPtr(@selector(moveToBegginingOfDocumentAndModifySelection:)), + : ToObjcSelectorPtr( + @selector(moveToBegginingOfDocumentAndModifySelection:)), aCommands); break; } if (aEvent.IsAlt()) { if (!aEvent.IsShift()) { - instance->AppendEditCommandsForSelector(ToObjcSelectorPtr(@selector(moveBackward:)), - aCommands); instance->AppendEditCommandsForSelector( - ToObjcSelectorPtr(@selector(moveToBeginningOfParagraph:)), aCommands); + ToObjcSelectorPtr(@selector(moveBackward:)), aCommands); + instance->AppendEditCommandsForSelector( + ToObjcSelectorPtr(@selector(moveToBeginningOfParagraph:)), + aCommands); break; } instance->AppendEditCommandsForSelector( - ToObjcSelectorPtr(@selector(moveParagraphBackwardAndModifySelection:)), aCommands); + ToObjcSelectorPtr(@selector + (moveParagraphBackwardAndModifySelection:)), + aCommands); break; } instance->AppendEditCommandsForSelector( - !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveUp:)) - : ToObjcSelectorPtr(@selector(moveUpAndModifySelection:)), + !aEvent.IsShift() + ? ToObjcSelectorPtr(@selector(moveUp:)) + : ToObjcSelectorPtr(@selector(moveUpAndModifySelection:)), aCommands); break; case KEY_NAME_INDEX_ArrowDown: @@ -573,32 +618,37 @@ void NativeKeyBindings::GetEditCommandsForTests(NativeKeyBindingsType aType, instance->AppendEditCommandsForSelector( !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveToEndOfDocument:)) - : ToObjcSelectorPtr(@selector(moveToEndOfDocumentAndModifySelection:)), + : ToObjcSelectorPtr(@selector + (moveToEndOfDocumentAndModifySelection:)), aCommands); break; } if (aEvent.IsAlt()) { if (!aEvent.IsShift()) { - instance->AppendEditCommandsForSelector(ToObjcSelectorPtr(@selector(moveForward:)), - aCommands); + instance->AppendEditCommandsForSelector( + ToObjcSelectorPtr(@selector(moveForward:)), aCommands); instance->AppendEditCommandsForSelector( ToObjcSelectorPtr(@selector(moveToEndOfParagraph:)), aCommands); break; } instance->AppendEditCommandsForSelector( - ToObjcSelectorPtr(@selector(moveParagraphForwardAndModifySelection:)), aCommands); + ToObjcSelectorPtr(@selector + (moveParagraphForwardAndModifySelection:)), + aCommands); break; } instance->AppendEditCommandsForSelector( - !aEvent.IsShift() ? ToObjcSelectorPtr(@selector(moveDown:)) - : ToObjcSelectorPtr(@selector(moveDownAndModifySelection:)), + !aEvent.IsShift() + ? ToObjcSelectorPtr(@selector(moveDown:)) + : ToObjcSelectorPtr(@selector(moveDownAndModifySelection:)), aCommands); break; default: break; } - instance->LogEditCommands(aCommands, "NativeKeyBindings::GetEditCommandsForTests"); + instance->LogEditCommands(aCommands, + "NativeKeyBindings::GetEditCommandsForTests"); } } // namespace widget diff --git a/widget/cocoa/NativeMenuMac.mm b/widget/cocoa/NativeMenuMac.mm index 91b7294c9570..4efa48c53f59 100644 --- a/widget/cocoa/NativeMenuMac.mm +++ b/widget/cocoa/NativeMenuMac.mm @@ -37,7 +37,8 @@ namespace widget { NativeMenuMac::NativeMenuMac(dom::Element* aElement) : mElement(aElement), mContainerStatusBarItem(nil) { - MOZ_RELEASE_ASSERT(aElement->IsAnyOfXULElements(nsGkAtoms::menu, nsGkAtoms::menupopup)); + MOZ_RELEASE_ASSERT( + aElement->IsAnyOfXULElements(nsGkAtoms::menu, nsGkAtoms::menupopup)); mMenuGroupOwner = new nsMenuGroupOwnerX(aElement, nullptr); mMenu = MakeRefPtr(nullptr, mMenuGroupOwner, aElement); mMenu->SetObserver(this); @@ -78,9 +79,11 @@ bool NativeMenuMac::ActivateNativeMenuItemAt(const nsAString& aIndexString) { nsMenuUtilsX::CheckNativeMenuConsistency(menu); NSString* locationString = - [NSString stringWithCharacters:reinterpret_cast(aIndexString.BeginReading()) + [NSString stringWithCharacters:reinterpret_cast( + aIndexString.BeginReading()) length:aIndexString.Length()]; - NSMenuItem* item = nsMenuUtilsX::NativeMenuItemWithLocation(menu, locationString, false); + NSMenuItem* item = + nsMenuUtilsX::NativeMenuItemWithLocation(menu, locationString, false); // We can't perform an action on an item with a submenu, that will raise // an obj-c exception. @@ -106,9 +109,11 @@ void NativeMenuMac::ForceUpdateNativeMenuAt(const nsAString& aIndexString) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; NSString* locationString = - [NSString stringWithCharacters:reinterpret_cast(aIndexString.BeginReading()) + [NSString stringWithCharacters:reinterpret_cast( + aIndexString.BeginReading()) length:aIndexString.Length()]; - NSArray* indexes = [locationString componentsSeparatedByString:@"|"]; + NSArray* indexes = + [locationString componentsSeparatedByString:@"|"]; RefPtr currentMenu = mMenu.get(); // now find the correct submenu @@ -124,7 +129,9 @@ void NativeMenuMac::ForceUpdateNativeMenuAt(const nsAString& aIndexString) { } RefPtr content = targetMenu->match( [](const RefPtr& aMenu) { return aMenu->Content(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->Content(); }); + [](const RefPtr& aMenuItem) { + return aMenuItem->Content(); + }); if (!nsMenuUtilsX::NodeIsHiddenOrCollapsed(content)) { visible++; if (targetMenu->is>() && visible == (targetIndex + 1)) { @@ -175,8 +182,8 @@ void NativeMenuMac::OnMenuWillOpen(dom::Element* aPopupElement) { return; } - // Our caller isn't keeping us alive, so make sure we stay alive throughout this function in case - // one of the observer notifications destroys us. + // Our caller isn't keeping us alive, so make sure we stay alive throughout + // this function in case one of the observer notifications destroys us. RefPtr kungFuDeathGrip(this); for (NativeMenu::Observer* observer : mObservers.Clone()) { @@ -185,8 +192,8 @@ void NativeMenuMac::OnMenuWillOpen(dom::Element* aPopupElement) { } void NativeMenuMac::OnMenuDidOpen(dom::Element* aPopupElement) { - // Our caller isn't keeping us alive, so make sure we stay alive throughout this function in case - // one of the observer notifications destroys us. + // Our caller isn't keeping us alive, so make sure we stay alive throughout + // this function in case one of the observer notifications destroys us. RefPtr kungFuDeathGrip(this); for (NativeMenu::Observer* observer : mObservers.Clone()) { @@ -200,8 +207,8 @@ void NativeMenuMac::OnMenuDidOpen(dom::Element* aPopupElement) { void NativeMenuMac::OnMenuWillActivateItem(dom::Element* aPopupElement, dom::Element* aMenuItemElement) { - // Our caller isn't keeping us alive, so make sure we stay alive throughout this function in case - // one of the observer notifications destroys us. + // Our caller isn't keeping us alive, so make sure we stay alive throughout + // this function in case one of the observer notifications destroys us. RefPtr kungFuDeathGrip(this); for (NativeMenu::Observer* observer : mObservers.Clone()) { @@ -210,8 +217,8 @@ void NativeMenuMac::OnMenuWillActivateItem(dom::Element* aPopupElement, } void NativeMenuMac::OnMenuClosed(dom::Element* aPopupElement) { - // Our caller isn't keeping us alive, so make sure we stay alive throughout this function in case - // one of the observer notifications destroys us. + // Our caller isn't keeping us alive, so make sure we stay alive throughout + // this function in case one of the observer notifications destroys us. RefPtr kungFuDeathGrip(this); for (NativeMenu::Observer* observer : mObservers.Clone()) { @@ -236,7 +243,8 @@ static NSAppearance* NativeAppearanceForContent(nsIContent* aContent) { return NSAppearanceForColorScheme(LookAndFeel::ColorSchemeForFrame(f)); } -void NativeMenuMac::ShowAsContextMenu(nsIFrame* aClickedFrame, const CSSIntPoint& aPosition, +void NativeMenuMac::ShowAsContextMenu(nsIFrame* aClickedFrame, + const CSSIntPoint& aPosition, bool aIsContextMenu) { nsPresContext* pc = aClickedFrame->PresContext(); auto cssToDesktopScale = @@ -250,24 +258,29 @@ void NativeMenuMac::ShowAsContextMenu(nsIFrame* aClickedFrame, const CSSIntPoint NSAppearance* appearance = NativeAppearanceForContent(mMenu->Content()); NSPoint locationOnScreen = nsCocoaUtils::GeckoPointToCocoaPoint(desktopPoint); - // Let the MOZMenuOpeningCoordinator do the actual opening, so that this ShowAsContextMenu call - // does not spawn a nested event loop, which would be surprising to our callers. - mOpeningHandle = [MOZMenuOpeningCoordinator.sharedInstance asynchronouslyOpenMenu:menu - atScreenPosition:locationOnScreen - forView:view - withAppearance:appearance - asContextMenu:aIsContextMenu]; + // Let the MOZMenuOpeningCoordinator do the actual opening, so that this + // ShowAsContextMenu call does not spawn a nested event loop, which would be + // surprising to our callers. + mOpeningHandle = [MOZMenuOpeningCoordinator.sharedInstance + asynchronouslyOpenMenu:menu + atScreenPosition:locationOnScreen + forView:view + withAppearance:appearance + asContextMenu:aIsContextMenu]; } bool NativeMenuMac::Close() { if (mOpeningHandle) { - // In case the menu was trying to open, but this Close() call interrupted it, cancel opening. - [MOZMenuOpeningCoordinator.sharedInstance cancelAsynchronousOpening:mOpeningHandle]; + // In case the menu was trying to open, but this Close() call interrupted + // it, cancel opening. + [MOZMenuOpeningCoordinator.sharedInstance + cancelAsynchronousOpening:mOpeningHandle]; } return mMenu->Close(); } -RefPtr NativeMenuMac::GetOpenMenuContainingElement(dom::Element* aElement) { +RefPtr NativeMenuMac::GetOpenMenuContainingElement( + dom::Element* aElement) { nsTArray> submenuChain; RefPtr currentElement = aElement->GetParentElement(); while (currentElement && currentElement != mElement) { @@ -281,7 +294,8 @@ RefPtr NativeMenuMac::GetOpenMenuContainingElement(dom::Element* aEleme return nullptr; } - // Traverse submenuChain from shallow to deep, to find the nsMenuX that contains aElement. + // Traverse submenuChain from shallow to deep, to find the nsMenuX that + // contains aElement. submenuChain.Reverse(); RefPtr menu = mMenu; for (const auto& submenu : submenuChain) { @@ -321,7 +335,8 @@ static NSEventModifierFlags ConvertModifierFlags(Modifiers aModifiers) { return flags; } -void NativeMenuMac::ActivateItem(dom::Element* aItemElement, Modifiers aModifiers, int16_t aButton, +void NativeMenuMac::ActivateItem(dom::Element* aItemElement, + Modifiers aModifiers, int16_t aButton, ErrorResult& aRv) { RefPtr menu = GetOpenMenuContainingElement(aItemElement); if (!menu) { @@ -343,27 +358,29 @@ void NativeMenuMac::ActivateItem(dom::Element* aItemElement, Modifiers aModifier NSMenuItem* nativeItem = [item->NativeNSMenuItem() retain]; // First, initiate the closing of the NSMenu. - // This synchronously calls the menu delegate's menuDidClose handler. So menuDidClose is - // what runs first; this matches the order of events for user-initiated menu item activation. - // This call doesn't immediately hide the menu; the menu only hides once the stack unwinds - // from NSMenu's nested "tracking" event loop. + // This synchronously calls the menu delegate's menuDidClose handler. So + // menuDidClose is what runs first; this matches the order of events for + // user-initiated menu item activation. This call doesn't immediately hide the + // menu; the menu only hides once the stack unwinds from NSMenu's nested + // "tracking" event loop. [mMenu->NativeNSMenu() cancelTrackingWithoutAnimation]; - // Next, call OnWillActivateItem. This also matches the order of calls that happen when a user - // activates a menu item in the real world: -[MenuDelegate menu:willActivateItem:] runs after - // menuDidClose. + // Next, call OnWillActivateItem. This also matches the order of calls that + // happen when a user activates a menu item in the real world: -[MenuDelegate + // menu:willActivateItem:] runs after menuDidClose. menu->OnWillActivateItem(nativeItem); - // Finally, call ActivateItemAfterClosing. This also mimics the order in the real world: - // menuItemHit is called after menu:willActivateItem:. - menu->ActivateItemAfterClosing(std::move(item), ConvertModifierFlags(aModifiers), aButton); + // Finally, call ActivateItemAfterClosing. This also mimics the order in the + // real world: menuItemHit is called after menu:willActivateItem:. + menu->ActivateItemAfterClosing(std::move(item), + ConvertModifierFlags(aModifiers), aButton); // Tell our native event loop that it should not process any more work before // unwinding the stack, so that we can get out of the menu's nested event loop - // as fast as possible. This was needed to fix spurious failures in tests, where - // a call to cancelTrackingWithoutAnimation was ignored if more native events were - // processed before the event loop was exited. As a result, the menu stayed open - // forever and the test never finished. + // as fast as possible. This was needed to fix spurious failures in tests, + // where a call to cancelTrackingWithoutAnimation was ignored if more native + // events were processed before the event loop was exited. As a result, the + // menu stayed open forever and the test never finished. MOZMenuOpeningCoordinator.needToUnwindForMenuClosing = YES; [nativeItem release]; diff --git a/widget/cocoa/NativeMenuSupport.mm b/widget/cocoa/NativeMenuSupport.mm index 98f9fc045edb..2e94f6f7cfd9 100644 --- a/widget/cocoa/NativeMenuSupport.mm +++ b/widget/cocoa/NativeMenuSupport.mm @@ -14,14 +14,19 @@ namespace mozilla::widget { -void NativeMenuSupport::CreateNativeMenuBar(nsIWidget* aParent, dom::Element* aMenuBarElement) { - MOZ_RELEASE_ASSERT(NS_IsMainThread(), "Attempting to create native menu bar on wrong thread!"); +void NativeMenuSupport::CreateNativeMenuBar(nsIWidget* aParent, + dom::Element* aMenuBarElement) { + MOZ_RELEASE_ASSERT(NS_IsMainThread(), + "Attempting to create native menu bar on wrong thread!"); - // Create the menubar and give it to the parent window. The parent takes ownership. - static_cast(aParent)->SetMenuBar(MakeRefPtr(aMenuBarElement)); + // Create the menubar and give it to the parent window. The parent takes + // ownership. + static_cast(aParent)->SetMenuBar( + MakeRefPtr(aMenuBarElement)); } -already_AddRefed NativeMenuSupport::CreateNativeContextMenu(dom::Element* aPopup) { +already_AddRefed NativeMenuSupport::CreateNativeContextMenu( + dom::Element* aPopup) { return MakeAndAddRef(aPopup); } diff --git a/widget/cocoa/OSXNotificationCenter.mm b/widget/cocoa/OSXNotificationCenter.mm index 854bcadb13bc..07cb026f1fea 100644 --- a/widget/cocoa/OSXNotificationCenter.mm +++ b/widget/cocoa/OSXNotificationCenter.mm @@ -55,7 +55,8 @@ using namespace mozilla; - (void)_removeDisplayedNotification:(id)notification; @end -@interface mozNotificationCenterDelegate : NSObject { +@interface mozNotificationCenterDelegate + : NSObject { OSXNotificationCenter* mOSXNC; } - (id)initWithOSXNC:(OSXNotificationCenter*)osxnc; @@ -78,11 +79,12 @@ using namespace mozilla; didActivateNotification:(id)notification { unsigned long long additionalActionIndex = ULLONG_MAX; if ([notification respondsToSelector:@selector(_alternateActionIndex)]) { - NSNumber* alternateActionIndex = [(NSObject*)notification valueForKey:@"_alternateActionIndex"]; + NSNumber* alternateActionIndex = + [(NSObject*)notification valueForKey:@"_alternateActionIndex"]; additionalActionIndex = [alternateActionIndex unsignedLongLongValue]; } - mOSXNC->OnActivate([[notification userInfo] valueForKey:@"name"], notification.activationType, - additionalActionIndex); + mOSXNC->OnActivate([[notification userInfo] valueForKey:@"name"], + notification.activationType, additionalActionIndex); } - (BOOL)userNotificationCenter:(id)center @@ -100,7 +102,8 @@ using namespace mozilla; } } -// This is an undocumented method that we need to be notified if a user clicks the close button. +// This is an undocumented method that we need to be notified if a user clicks +// the close button. - (void)userNotificationCenter:(id)center didDismissAlert:(id)notification { NSString* name = [[notification userInfo] valueForKey:@"name"]; @@ -122,7 +125,8 @@ class OSXNotificationInfo final : public nsISupports { public: NS_DECL_ISUPPORTS - OSXNotificationInfo(NSString* name, nsIObserver* observer, const nsAString& alertCookie); + OSXNotificationInfo(NSString* name, nsIObserver* observer, + const nsAString& alertCookie); NSString* mName; nsCOMPtr mObserver; @@ -183,50 +187,56 @@ OSXNotificationCenter::~OSXNotificationCenter() { NS_OBJC_END_TRY_IGNORE_BLOCK; } -NS_IMPL_ISUPPORTS(OSXNotificationCenter, nsIAlertsService, nsIAlertsIconData, nsIAlertsDoNotDisturb, - nsIAlertNotificationImageListener) +NS_IMPL_ISUPPORTS(OSXNotificationCenter, nsIAlertsService, nsIAlertsIconData, + nsIAlertsDoNotDisturb, nsIAlertNotificationImageListener) nsresult OSXNotificationCenter::Init() { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - return (!!NSClassFromString(@"NSUserNotification")) ? NS_OK : NS_ERROR_FAILURE; + return (!!NSClassFromString(@"NSUserNotification")) ? NS_OK + : NS_ERROR_FAILURE; NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } NS_IMETHODIMP OSXNotificationCenter::ShowAlertNotification( - const nsAString& aImageUrl, const nsAString& aAlertTitle, const nsAString& aAlertText, - bool aAlertTextClickable, const nsAString& aAlertCookie, nsIObserver* aAlertListener, + const nsAString& aImageUrl, const nsAString& aAlertTitle, + const nsAString& aAlertText, bool aAlertTextClickable, + const nsAString& aAlertCookie, nsIObserver* aAlertListener, const nsAString& aAlertName, const nsAString& aBidi, const nsAString& aLang, const nsAString& aData, nsIPrincipal* aPrincipal, bool aInPrivateBrowsing, bool aRequireInteraction) { - nsCOMPtr alert = do_CreateInstance(ALERT_NOTIFICATION_CONTRACTID); + nsCOMPtr alert = + do_CreateInstance(ALERT_NOTIFICATION_CONTRACTID); NS_ENSURE_TRUE(alert, NS_ERROR_FAILURE); // vibrate is unused for now nsTArray vibrate; - nsresult rv = alert->Init(aAlertName, aImageUrl, aAlertTitle, aAlertText, aAlertTextClickable, - aAlertCookie, aBidi, aLang, aData, aPrincipal, aInPrivateBrowsing, + nsresult rv = alert->Init(aAlertName, aImageUrl, aAlertTitle, aAlertText, + aAlertTextClickable, aAlertCookie, aBidi, aLang, + aData, aPrincipal, aInPrivateBrowsing, aRequireInteraction, false, vibrate); NS_ENSURE_SUCCESS(rv, rv); return ShowAlert(alert, aAlertListener); } NS_IMETHODIMP -OSXNotificationCenter::ShowPersistentNotification(const nsAString& aPersistentData, - nsIAlertNotification* aAlert, - nsIObserver* aAlertListener) { +OSXNotificationCenter::ShowPersistentNotification( + const nsAString& aPersistentData, nsIAlertNotification* aAlert, + nsIObserver* aAlertListener) { return ShowAlert(aAlert, aAlertListener); } NS_IMETHODIMP -OSXNotificationCenter::ShowAlert(nsIAlertNotification* aAlert, nsIObserver* aAlertListener) { +OSXNotificationCenter::ShowAlert(nsIAlertNotification* aAlert, + nsIObserver* aAlertListener) { return ShowAlertWithIconData(aAlert, aAlertListener, 0, nullptr); } NS_IMETHODIMP OSXNotificationCenter::ShowAlertWithIconData(nsIAlertNotification* aAlert, - nsIObserver* aAlertListener, uint32_t aIconSize, + nsIObserver* aAlertListener, + uint32_t aIconSize, const uint8_t* aIconData) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; @@ -248,13 +258,16 @@ OSXNotificationCenter::ShowAlertWithIconData(nsIAlertNotification* aAlert, rv = aAlert->GetSource(hostPort); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr bundle; - nsCOMPtr sbs = do_GetService(NS_STRINGBUNDLE_CONTRACTID); - sbs->CreateBundle("chrome://alerts/locale/alert.properties", getter_AddRefs(bundle)); + nsCOMPtr sbs = + do_GetService(NS_STRINGBUNDLE_CONTRACTID); + sbs->CreateBundle("chrome://alerts/locale/alert.properties", + getter_AddRefs(bundle)); if (!hostPort.IsEmpty() && bundle) { AutoTArray formatStrings = {hostPort}; nsAutoString notificationSource; - bundle->FormatStringFromName("source.label", formatStrings, notificationSource); + bundle->FormatStringFromName("source.label", formatStrings, + notificationSource); notification.subtitle = nsCocoaUtils::ToNSString(notificationSource); } @@ -268,17 +281,19 @@ OSXNotificationCenter::ShowAlertWithIconData(nsIAlertNotification* aAlert, notification.soundName = isSilent ? nil : NSUserNotificationDefaultSoundName; notification.hasActionButton = NO; - // If this is not an application/extension alert, show additional actions dealing with - // permissions. + // If this is not an application/extension alert, show additional actions + // dealing with permissions. bool isActionable; - if (bundle && NS_SUCCEEDED(aAlert->GetActionable(&isActionable)) && isActionable) { - nsAutoString closeButtonTitle, actionButtonTitle, disableButtonTitle, settingsButtonTitle; + if (bundle && NS_SUCCEEDED(aAlert->GetActionable(&isActionable)) && + isActionable) { + nsAutoString closeButtonTitle, actionButtonTitle, disableButtonTitle, + settingsButtonTitle; bundle->GetStringFromName("closeButton.title", closeButtonTitle); bundle->GetStringFromName("actionButton.label", actionButtonTitle); if (!hostPort.IsEmpty()) { AutoTArray formatStrings = {hostPort}; - bundle->FormatStringFromName("webActions.disableForOrigin.label", formatStrings, - disableButtonTitle); + bundle->FormatStringFromName("webActions.disableForOrigin.label", + formatStrings, disableButtonTitle); } bundle->GetStringFromName("webActions.settings.label", settingsButtonTitle); @@ -288,15 +303,20 @@ OSXNotificationCenter::ShowAlertWithIconData(nsIAlertNotification* aAlert, // Notification Center preferences, and doesn't support the alternate // action menu. if ([notification respondsToSelector:@selector(set_showsButtons:)] && - [notification respondsToSelector:@selector(set_alwaysShowAlternateActionMenu:)] && - [notification respondsToSelector:@selector(set_alternateActionButtonTitles:)]) { + [notification + respondsToSelector:@selector(set_alwaysShowAlternateActionMenu:)] && + [notification + respondsToSelector:@selector(set_alternateActionButtonTitles:)]) { notification.hasActionButton = YES; - notification.actionButtonTitle = nsCocoaUtils::ToNSString(actionButtonTitle); + notification.actionButtonTitle = + nsCocoaUtils::ToNSString(actionButtonTitle); [(NSObject*)notification setValue:@(YES) forKey:@"_showsButtons"]; - [(NSObject*)notification setValue:@(YES) forKey:@"_alwaysShowAlternateActionMenu"]; + [(NSObject*)notification setValue:@(YES) + forKey:@"_alwaysShowAlternateActionMenu"]; [(NSObject*)notification setValue:@[ - nsCocoaUtils::ToNSString(disableButtonTitle), nsCocoaUtils::ToNSString(settingsButtonTitle) + nsCocoaUtils::ToNSString(disableButtonTitle), + nsCocoaUtils::ToNSString(settingsButtonTitle) ] forKey:@"_alternateActionButtonTitles"]; } @@ -315,19 +335,22 @@ OSXNotificationCenter::ShowAlertWithIconData(nsIAlertNotification* aAlert, if (!alertName) { return NS_ERROR_FAILURE; } - notification.userInfo = - [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:alertName, nil] - forKeys:[NSArray arrayWithObjects:@"name", nil]]; + notification.userInfo = [NSDictionary + dictionaryWithObjects:[NSArray arrayWithObjects:alertName, nil] + forKeys:[NSArray arrayWithObjects:@"name", nil]]; nsAutoString cookie; rv = aAlert->GetCookie(cookie); NS_ENSURE_SUCCESS(rv, rv); - OSXNotificationInfo* osxni = new OSXNotificationInfo(alertName, aAlertListener, cookie); + OSXNotificationInfo* osxni = + new OSXNotificationInfo(alertName, aAlertListener, cookie); // Show the favicon if supported on this version of OS X. - if (aIconSize > 0 && [notification respondsToSelector:@selector(set_identityImage:)] && - [notification respondsToSelector:@selector(set_identityImageHasBorder:)]) { + if (aIconSize > 0 && + [notification respondsToSelector:@selector(set_identityImage:)] && + [notification + respondsToSelector:@selector(set_identityImageHasBorder:)]) { NSData* iconData = [NSData dataWithBytes:aIconData length:aIconSize]; NSImage* icon = [[[NSImage alloc] initWithData:iconData] autorelease]; @@ -339,8 +362,8 @@ OSXNotificationCenter::ShowAlertWithIconData(nsIAlertNotification* aAlert, rv = aAlert->GetInPrivateBrowsing(&inPrivateBrowsing); NS_ENSURE_SUCCESS(rv, rv); - // Show the notification without waiting for an image if there is no icon URL or - // notification icons are not supported on this version of OS X. + // Show the notification without waiting for an image if there is no icon URL + // or notification icons are not supported on this version of OS X. if (![unClass instancesRespondToSelector:@selector(setContentImage:)]) { CloseAlertCocoaString(alertName); mActiveAlerts.AppendElement(osxni); @@ -353,7 +376,8 @@ OSXNotificationCenter::ShowAlertWithIconData(nsIAlertNotification* aAlert, mPendingAlerts.AppendElement(osxni); osxni->mPendingNotification = notification; // Wait six seconds for the image to load. - rv = aAlert->LoadImage(6000, this, osxni, getter_AddRefs(osxni->mIconRequest)); + rv = aAlert->LoadImage(6000, this, osxni, + getter_AddRefs(osxni->mIconRequest)); if (NS_WARN_IF(NS_FAILED(rv))) { ShowPendingNotification(osxni); } @@ -365,7 +389,8 @@ OSXNotificationCenter::ShowAlertWithIconData(nsIAlertNotification* aAlert, } NS_IMETHODIMP -OSXNotificationCenter::CloseAlert(const nsAString& aAlertName, bool aContextClosed) { +OSXNotificationCenter::CloseAlert(const nsAString& aAlertName, + bool aContextClosed) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; NSString* alertName = nsCocoaUtils::ToNSString(aAlertName); @@ -396,7 +421,8 @@ void OSXNotificationCenter::CloseAlertCocoaString(NSString* aAlertName) { OSXNotificationInfo* osxni = mActiveAlerts[i]; if ([aAlertName isEqualToString:osxni->mName]) { if (osxni->mObserver) { - osxni->mObserver->Observe(nullptr, "alertfinished", osxni->mCookie.get()); + osxni->mObserver->Observe(nullptr, "alertfinished", + osxni->mCookie.get()); } if (osxni->mIconRequest) { osxni->mIconRequest->Cancel(NS_BINDING_ABORTED); @@ -410,9 +436,9 @@ void OSXNotificationCenter::CloseAlertCocoaString(NSString* aAlertName) { NS_OBJC_END_TRY_IGNORE_BLOCK; } -void OSXNotificationCenter::OnActivate(NSString* aAlertName, - NSUserNotificationActivationType aActivationType, - unsigned long long aAdditionalActionIndex) { +void OSXNotificationCenter::OnActivate( + NSString* aAlertName, NSUserNotificationActivationType aActivationType, + unsigned long long aAdditionalActionIndex) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; if (!aAlertName) { @@ -428,18 +454,22 @@ void OSXNotificationCenter::OnActivate(NSString* aAlertName, case NSUserNotificationActivationTypeActionButtonClicked: switch (aAdditionalActionIndex) { case OSXNotificationActionDisable: - osxni->mObserver->Observe(nullptr, "alertdisablecallback", osxni->mCookie.get()); + osxni->mObserver->Observe(nullptr, "alertdisablecallback", + osxni->mCookie.get()); break; case OSXNotificationActionSettings: - osxni->mObserver->Observe(nullptr, "alertsettingscallback", osxni->mCookie.get()); + osxni->mObserver->Observe(nullptr, "alertsettingscallback", + osxni->mCookie.get()); break; default: - NS_WARNING("Unknown NSUserNotification additional action clicked"); + NS_WARNING( + "Unknown NSUserNotification additional action clicked"); break; } break; default: - osxni->mObserver->Observe(nullptr, "alertclickcallback", osxni->mCookie.get()); + osxni->mObserver->Observe(nullptr, "alertclickcallback", + osxni->mCookie.get()); break; } } @@ -450,7 +480,8 @@ void OSXNotificationCenter::OnActivate(NSString* aAlertName, NS_OBJC_END_TRY_IGNORE_BLOCK; } -void OSXNotificationCenter::ShowPendingNotification(OSXNotificationInfo* osxni) { +void OSXNotificationCenter::ShowPendingNotification( + OSXNotificationInfo* osxni) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; if (osxni->mIconRequest) { @@ -496,7 +527,8 @@ OSXNotificationCenter::OnImageMissing(nsISupports* aUserData) { } NS_IMETHODIMP -OSXNotificationCenter::OnImageReady(nsISupports* aUserData, imgIRequest* aRequest) { +OSXNotificationCenter::OnImageReady(nsISupports* aUserData, + imgIRequest* aRequest) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; nsCOMPtr image; @@ -511,9 +543,10 @@ OSXNotificationCenter::OnImageReady(nsISupports* aUserData, imgIRequest* aReques } NSImage* cocoaImage = nil; - // TODO: Pass pres context / ComputedStyle here to support context paint properties - nsCocoaUtils::CreateDualRepresentationNSImageFromImageContainer(image, imgIContainer::FRAME_FIRST, - nullptr, nullptr, &cocoaImage); + // TODO: Pass pres context / ComputedStyle here to support context paint + // properties + nsCocoaUtils::CreateDualRepresentationNSImageFromImageContainer( + image, imgIContainer::FRAME_FIRST, nullptr, nullptr, &cocoaImage); (osxni->mPendingNotification).contentImage = cocoaImage; [cocoaImage release]; ShowPendingNotification(osxni); @@ -525,7 +558,9 @@ OSXNotificationCenter::OnImageReady(nsISupports* aUserData, imgIRequest* aReques // nsIAlertsDoNotDisturb NS_IMETHODIMP -OSXNotificationCenter::GetManualDoNotDisturb(bool* aRetVal) { return NS_ERROR_NOT_IMPLEMENTED; } +OSXNotificationCenter::GetManualDoNotDisturb(bool* aRetVal) { + return NS_ERROR_NOT_IMPLEMENTED; +} NS_IMETHODIMP OSXNotificationCenter::SetManualDoNotDisturb(bool aDoNotDisturb) { diff --git a/widget/cocoa/ScreenHelperCocoa.mm b/widget/cocoa/ScreenHelperCocoa.mm index 27c18bbfdf9c..57e1313320c5 100644 --- a/widget/cocoa/ScreenHelperCocoa.mm +++ b/widget/cocoa/ScreenHelperCocoa.mm @@ -79,19 +79,20 @@ ScreenHelperCocoa::~ScreenHelperCocoa() { static already_AddRefed MakeScreen(NSScreen* aScreen) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - DesktopToLayoutDeviceScale contentsScaleFactor(nsCocoaUtils::GetBackingScaleFactor(aScreen)); + DesktopToLayoutDeviceScale contentsScaleFactor( + nsCocoaUtils::GetBackingScaleFactor(aScreen)); CSSToLayoutDeviceScale defaultCssScaleFactor(contentsScaleFactor.scale); NSRect frame = [aScreen frame]; - LayoutDeviceIntRect rect = - nsCocoaUtils::CocoaRectToGeckoRectDevPix(frame, contentsScaleFactor.scale); + LayoutDeviceIntRect rect = nsCocoaUtils::CocoaRectToGeckoRectDevPix( + frame, contentsScaleFactor.scale); frame = [aScreen visibleFrame]; - LayoutDeviceIntRect availRect = - nsCocoaUtils::CocoaRectToGeckoRectDevPix(frame, contentsScaleFactor.scale); + LayoutDeviceIntRect availRect = nsCocoaUtils::CocoaRectToGeckoRectDevPix( + frame, contentsScaleFactor.scale); // aScreen may be capable of displaying multiple pixel depths, for example by - // transitioning to an HDR-capable depth when required by a window displayed on - // the screen. We want to note the maximum capabilities of the screen, so we use - // the largest depth it offers. + // transitioning to an HDR-capable depth when required by a window displayed + // on the screen. We want to note the maximum capabilities of the screen, so + // we use the largest depth it offers. uint32_t pixelDepth = 0; const NSWindowDepth* depths = [aScreen supportedWindowDepths]; for (size_t d = 0; NSWindowDepth depth = depths[d]; d++) { @@ -116,16 +117,17 @@ static already_AddRefed MakeScreen(NSScreen* aScreen) { dpi = rect.height / (heightMM / MM_PER_INCH_FLOAT); } MOZ_LOG(sScreenLog, LogLevel::Debug, - ("New screen [%d %d %d %d (%d %d %d %d) %d %f %f %f]", rect.x, rect.y, rect.width, - rect.height, availRect.x, availRect.y, availRect.width, availRect.height, pixelDepth, - contentsScaleFactor.scale, defaultCssScaleFactor.scale, dpi)); + ("New screen [%d %d %d %d (%d %d %d %d) %d %f %f %f]", rect.x, rect.y, + rect.width, rect.height, availRect.x, availRect.y, availRect.width, + availRect.height, pixelDepth, contentsScaleFactor.scale, + defaultCssScaleFactor.scale, dpi)); // Getting the refresh rate is a little hard on OS X. We could use // CVDisplayLinkGetNominalOutputVideoRefreshPeriod, but that's a little // involved. Ideally we could query it from vsync. For now, we leave it out. - RefPtr screen = - new Screen(rect, availRect, pixelDepth, pixelDepth, 0, contentsScaleFactor, - defaultCssScaleFactor, dpi, Screen::IsPseudoDisplay::No); + RefPtr screen = new Screen(rect, availRect, pixelDepth, pixelDepth, 0, + contentsScaleFactor, defaultCssScaleFactor, + dpi, Screen::IsPseudoDisplay::No); return screen.forget(); NS_OBJC_END_TRY_BLOCK_RETURN(nullptr); @@ -164,7 +166,8 @@ NSScreen* ScreenHelperCocoa::CocoaScreenForScreen(nsIScreen* aScreen) { aScreen->GetRect(&rect.x, &rect.y, &rect.width, &rect.height); aScreen->GetContentsScaleFactor(&scale); NSRect frame = [screen frame]; - LayoutDeviceIntRect frameRect = nsCocoaUtils::CocoaRectToGeckoRectDevPix(frame, scale); + LayoutDeviceIntRect frameRect = + nsCocoaUtils::CocoaRectToGeckoRectDevPix(frame, scale); if (rect == frameRect) { return screen; } diff --git a/widget/cocoa/TextInputHandler.mm b/widget/cocoa/TextInputHandler.mm index 1c293e459078..d38bc59823be 100644 --- a/widget/cocoa/TextInputHandler.mm +++ b/widget/cocoa/TextInputHandler.mm @@ -44,9 +44,11 @@ mozilla::LazyLogModule gKeyLog("KeyboardHandler"); // The behavior of `TextInputHandler` class is important both for logging // keyboard handler and IME handler. Therefore, the behavior is logged when // either `IMEHandler` or `KeyboardHandler` is set to `MOZ_LOG`. Therefore, -// you may not need to tell people `MOZ_LOG=IMEHandler:4,KeyboardHandler:4,sync`. -#define MOZ_LOG_KEY_OR_IME(aLogLevel, aArgs) \ - MOZ_LOG(MOZ_LOG_TEST(gIMELog, aLogLevel) ? gIMELog : gKeyLog, aLogLevel, aArgs) +// you may not need to tell people +// `MOZ_LOG=IMEHandler:4,KeyboardHandler:4,sync`. +#define MOZ_LOG_KEY_OR_IME(aLogLevel, aArgs) \ + MOZ_LOG(MOZ_LOG_TEST(gIMELog, aLogLevel) ? gIMELog : gKeyLog, aLogLevel, \ + aArgs) static const char* OnOrOff(bool aBool) { return aBool ? "ON" : "off"; } @@ -375,7 +377,8 @@ static const char* GetWindowLevelName(NSInteger aWindowLevel) { case kCGFloatingWindowLevelKey: return "kCGFloatingWindowLevelKey (NSFloatingWindowLevel)"; case kCGTornOffMenuWindowLevelKey: - return "kCGTornOffMenuWindowLevelKey (NSSubmenuWindowLevel, NSTornOffMenuWindowLevel)"; + return "kCGTornOffMenuWindowLevelKey (NSSubmenuWindowLevel, " + "NSTornOffMenuWindowLevel)"; case kCGDockWindowLevelKey: return "kCGDockWindowLevelKey (NSDockWindowLevel)"; case kCGMainMenuWindowLevelKey: @@ -409,7 +412,9 @@ static const char* GetWindowLevelName(NSInteger aWindowLevel) { } } -static bool IsControlChar(uint32_t aCharCode) { return aCharCode < ' ' || aCharCode == 0x7F; } +static bool IsControlChar(uint32_t aCharCode) { + return aCharCode < ' ' || aCharCode == 0x7F; +} static uint32_t gHandlerInstanceCount = 0; @@ -422,7 +427,8 @@ static void EnsureToLogAllKeyboardLayoutsAndIMEs() { } } -inline NSRange MakeNSRangeFrom(const Maybe>& aOffsetAndData) { +inline NSRange MakeNSRangeFrom( + const Maybe>& aOffsetAndData) { if (aOffsetAndData.isNothing()) { return NSMakeRange(NSNotFound, 0); } @@ -460,7 +466,8 @@ void TISInputSourceWrapper::Shutdown() { sCurrentInputSource = nullptr; } -bool TISInputSourceWrapper::TranslateToString(UInt32 aKeyCode, UInt32 aModifiers, UInt32 aKbType, +bool TISInputSourceWrapper::TranslateToString(UInt32 aKeyCode, + UInt32 aModifiers, UInt32 aKbType, nsAString& aStr) { aStr.Truncate(); @@ -470,10 +477,12 @@ bool TISInputSourceWrapper::TranslateToString(UInt32 aKeyCode, UInt32 aModifiers ("%p TISInputSourceWrapper::TranslateToString, aKeyCode=0x%X, " "aModifiers=0x%X, aKbType=0x%X UCKey=%p\n " "Shift: %s, Ctrl: %s, Opt: %s, Cmd: %s, CapsLock: %s, NumLock: %s", - this, static_cast(aKeyCode), static_cast(aModifiers), - static_cast(aKbType), UCKey, OnOrOff(aModifiers & shiftKey), - OnOrOff(aModifiers & controlKey), OnOrOff(aModifiers & optionKey), - OnOrOff(aModifiers & cmdKey), OnOrOff(aModifiers & alphaLock), + this, static_cast(aKeyCode), + static_cast(aModifiers), + static_cast(aKbType), UCKey, + OnOrOff(aModifiers & shiftKey), OnOrOff(aModifiers & controlKey), + OnOrOff(aModifiers & optionKey), OnOrOff(aModifiers & cmdKey), + OnOrOff(aModifiers & alphaLock), OnOrOff(aModifiers & kEventKeyModifierNumLockMask))); NS_ENSURE_TRUE(UCKey, false); @@ -481,12 +490,13 @@ bool TISInputSourceWrapper::TranslateToString(UInt32 aKeyCode, UInt32 aModifiers UInt32 deadKeyState = 0; UniCharCount len; UniChar chars[5]; - OSStatus err = ::UCKeyTranslate(UCKey, aKeyCode, kUCKeyActionDown, aModifiers >> 8, aKbType, - kUCKeyTranslateNoDeadKeysMask, &deadKeyState, 5, &len, chars); + OSStatus err = ::UCKeyTranslate( + UCKey, aKeyCode, kUCKeyActionDown, aModifiers >> 8, aKbType, + kUCKeyTranslateNoDeadKeysMask, &deadKeyState, 5, &len, chars); MOZ_LOG(gKeyLog, LogLevel::Info, - ("%p TISInputSourceWrapper::TranslateToString, err=0x%X, len=%zu", this, - static_cast(err), len)); + ("%p TISInputSourceWrapper::TranslateToString, err=0x%X, len=%zu", + this, static_cast(err), len)); NS_ENSURE_TRUE(err == noErr, false); if (len == 0) { @@ -506,10 +516,12 @@ bool TISInputSourceWrapper::TranslateToString(UInt32 aKeyCode, UInt32 aModifiers return true; } -uint32_t TISInputSourceWrapper::TranslateToChar(UInt32 aKeyCode, UInt32 aModifiers, +uint32_t TISInputSourceWrapper::TranslateToChar(UInt32 aKeyCode, + UInt32 aModifiers, UInt32 aKbType) { nsAutoString str; - if (!TranslateToString(aKeyCode, aModifiers, aKbType, str) || str.Length() != 1) { + if (!TranslateToString(aKeyCode, aModifiers, aKbType, str) || + str.Length() != 1) { return 0; } return static_cast(str.CharAt(0)); @@ -591,17 +603,20 @@ bool TISInputSourceWrapper::IsDeadKey(NSEvent* aNativeKeyEvent) { return IsDeadKey(nativeKeyCode, carbonState, kbType); } -bool TISInputSourceWrapper::IsDeadKey(UInt32 aKeyCode, UInt32 aModifiers, UInt32 aKbType) { +bool TISInputSourceWrapper::IsDeadKey(UInt32 aKeyCode, UInt32 aModifiers, + UInt32 aKbType) { const UCKeyboardLayout* UCKey = GetUCKeyboardLayout(); MOZ_LOG(gKeyLog, LogLevel::Info, ("%p TISInputSourceWrapper::IsDeadKey, aKeyCode=0x%X, " "aModifiers=0x%X, aKbType=0x%X UCKey=%p\n " "Shift: %s, Ctrl: %s, Opt: %s, Cmd: %s, CapsLock: %s, NumLock: %s", - this, static_cast(aKeyCode), static_cast(aModifiers), - static_cast(aKbType), UCKey, OnOrOff(aModifiers & shiftKey), - OnOrOff(aModifiers & controlKey), OnOrOff(aModifiers & optionKey), - OnOrOff(aModifiers & cmdKey), OnOrOff(aModifiers & alphaLock), + this, static_cast(aKeyCode), + static_cast(aModifiers), + static_cast(aKbType), UCKey, + OnOrOff(aModifiers & shiftKey), OnOrOff(aModifiers & controlKey), + OnOrOff(aModifiers & optionKey), OnOrOff(aModifiers & cmdKey), + OnOrOff(aModifiers & alphaLock), OnOrOff(aModifiers & kEventKeyModifierNumLockMask))); if (NS_WARN_IF(!UCKey)) { @@ -611,8 +626,9 @@ bool TISInputSourceWrapper::IsDeadKey(UInt32 aKeyCode, UInt32 aModifiers, UInt32 UInt32 deadKeyState = 0; UniCharCount len; UniChar chars[5]; - OSStatus err = ::UCKeyTranslate(UCKey, aKeyCode, kUCKeyActionDown, aModifiers >> 8, aKbType, 0, - &deadKeyState, 5, &len, chars); + OSStatus err = + ::UCKeyTranslate(UCKey, aKeyCode, kUCKeyActionDown, aModifiers >> 8, + aKbType, 0, &deadKeyState, 5, &len, chars); MOZ_LOG(gKeyLog, LogLevel::Info, ("%p TISInputSourceWrapper::IsDeadKey, err=0x%X, " @@ -630,7 +646,8 @@ void TISInputSourceWrapper::InitByInputSourceID(const char* aID) { Clear(); if (!aID) return; - CFStringRef idstr = ::CFStringCreateWithCString(kCFAllocatorDefault, aID, kCFStringEncodingASCII); + CFStringRef idstr = ::CFStringCreateWithCString(kCFAllocatorDefault, aID, + kCFStringEncodingASCII); InitByInputSourceID(idstr); ::CFRelease(idstr); } @@ -639,7 +656,8 @@ void TISInputSourceWrapper::InitByInputSourceID(const nsString& aID) { Clear(); if (aID.IsEmpty()) return; CFStringRef idstr = ::CFStringCreateWithCharacters( - kCFAllocatorDefault, reinterpret_cast(aID.get()), aID.Length()); + kCFAllocatorDefault, reinterpret_cast(aID.get()), + aID.Length()); InitByInputSourceID(idstr); ::CFRelease(idstr); } @@ -649,7 +667,8 @@ void TISInputSourceWrapper::InitByInputSourceID(const CFStringRef aID) { if (!aID) return; const void* keys[] = {kTISPropertyInputSourceID}; const void* values[] = {aID}; - CFDictionaryRef filter = ::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL); + CFDictionaryRef filter = + ::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL); NS_ASSERTION(filter, "failed to create the filter"); mInputSourceList = ::TISCreateInputSourceList(filter, true); ::CFRelease(filter); @@ -662,7 +681,8 @@ void TISInputSourceWrapper::InitByInputSourceID(const CFStringRef aID) { } } -void TISInputSourceWrapper::InitByLayoutID(SInt32 aLayoutID, bool aOverrideKeyboard) { +void TISInputSourceWrapper::InitByLayoutID(SInt32 aLayoutID, + bool aOverrideKeyboard) { // NOTE: Doument new layout IDs in TextInputHandler.h when you add ones. switch (aLayoutID) { case 0: @@ -766,7 +786,8 @@ void TISInputSourceWrapper::InitByCurrentInputMethodKeyboardLayoutOverride() { mKeyboardLayout = mInputSource; } -void TISInputSourceWrapper::InitByTISInputSourceRef(TISInputSourceRef aInputSource) { +void TISInputSourceWrapper::InitByTISInputSourceRef( + TISInputSourceRef aInputSource) { Clear(); mInputSource = aInputSource; if (IsKeyboardLayout()) { @@ -787,26 +808,31 @@ const UCKeyboardLayout* TISInputSourceWrapper::GetUCKeyboardLayout() { if (mUCKeyboardLayout) { return mUCKeyboardLayout; } - CFDataRef uchr = static_cast( - ::TISGetInputSourceProperty(mKeyboardLayout, kTISPropertyUnicodeKeyLayoutData)); + CFDataRef uchr = static_cast(::TISGetInputSourceProperty( + mKeyboardLayout, kTISPropertyUnicodeKeyLayoutData)); // We should be always able to get the layout here. NS_ENSURE_TRUE(uchr, nullptr); - mUCKeyboardLayout = reinterpret_cast(CFDataGetBytePtr(uchr)); + mUCKeyboardLayout = + reinterpret_cast(CFDataGetBytePtr(uchr)); return mUCKeyboardLayout; } bool TISInputSourceWrapper::GetBoolProperty(const CFStringRef aKey) { - CFBooleanRef ret = static_cast(::TISGetInputSourceProperty(mInputSource, aKey)); + CFBooleanRef ret = static_cast( + ::TISGetInputSourceProperty(mInputSource, aKey)); return ::CFBooleanGetValue(ret); } -bool TISInputSourceWrapper::GetStringProperty(const CFStringRef aKey, CFStringRef& aStr) { - aStr = static_cast(::TISGetInputSourceProperty(mInputSource, aKey)); +bool TISInputSourceWrapper::GetStringProperty(const CFStringRef aKey, + CFStringRef& aStr) { + aStr = + static_cast(::TISGetInputSourceProperty(mInputSource, aKey)); return aStr != nullptr; } -bool TISInputSourceWrapper::GetStringProperty(const CFStringRef aKey, nsAString& aStr) { +bool TISInputSourceWrapper::GetStringProperty(const CFStringRef aKey, + nsAString& aStr) { CFStringRef str; GetStringProperty(aKey, str); nsCocoaUtils::GetStringForNSString((const NSString*)str, aStr); @@ -824,7 +850,8 @@ bool TISInputSourceWrapper::IsIMEMode() { CFStringRef str; GetInputSourceType(str); NS_ENSURE_TRUE(str, false); - return ::CFStringCompare(kTISTypeKeyboardInputMode, str, 0) == kCFCompareEqualTo; + return ::CFStringCompare(kTISTypeKeyboardInputMode, str, 0) == + kCFCompareEqualTo; } bool TISInputSourceWrapper::IsKeyboardLayout() { @@ -837,8 +864,8 @@ bool TISInputSourceWrapper::IsKeyboardLayout() { bool TISInputSourceWrapper::GetLanguageList(CFArrayRef& aLanguageList) { NS_ENSURE_TRUE(mInputSource, false); - aLanguageList = static_cast( - ::TISGetInputSourceProperty(mInputSource, kTISPropertyInputSourceLanguages)); + aLanguageList = static_cast(::TISGetInputSourceProperty( + mInputSource, kTISPropertyInputSourceLanguages)); return aLanguageList != nullptr; } @@ -847,7 +874,8 @@ bool TISInputSourceWrapper::GetPrimaryLanguage(CFStringRef& aPrimaryLanguage) { CFArrayRef langList; NS_ENSURE_TRUE(GetLanguageList(langList), false); if (::CFArrayGetCount(langList) == 0) return false; - aPrimaryLanguage = static_cast(::CFArrayGetValueAtIndex(langList, 0)); + aPrimaryLanguage = + static_cast(::CFArrayGetValueAtIndex(langList, 0)); return aPrimaryLanguage != nullptr; } @@ -855,7 +883,8 @@ bool TISInputSourceWrapper::GetPrimaryLanguage(nsAString& aPrimaryLanguage) { NS_ENSURE_TRUE(mInputSource, false); CFStringRef primaryLanguage; NS_ENSURE_TRUE(GetPrimaryLanguage(primaryLanguage), false); - nsCocoaUtils::GetStringForNSString((const NSString*)primaryLanguage, aPrimaryLanguage); + nsCocoaUtils::GetStringForNSString((const NSString*)primaryLanguage, + aPrimaryLanguage); return !aPrimaryLanguage.IsEmpty(); } @@ -901,13 +930,15 @@ void TISInputSourceWrapper::Clear() { mOverrideKeyboard = false; } -bool TISInputSourceWrapper::IsPrintableKeyEvent(NSEvent* aNativeKeyEvent) const { +bool TISInputSourceWrapper::IsPrintableKeyEvent( + NSEvent* aNativeKeyEvent) const { UInt32 nativeKeyCode = [aNativeKeyEvent keyCode]; bool isPrintableKey = !TextInputHandler::IsSpecialGeckoKey(nativeKeyCode); if (isPrintableKey && [aNativeKeyEvent type] != NSEventTypeKeyDown && [aNativeKeyEvent type] != NSEventTypeKeyUp) { - NS_WARNING("Why would a printable key not be an NSEventTypeKeyDown or NSEventTypeKeyUp event?"); + NS_WARNING("Why would a printable key not be an NSEventTypeKeyDown or " + "NSEventTypeKeyUp event?"); isPrintableKey = false; } return isPrintableKey; @@ -922,10 +953,9 @@ UInt32 TISInputSourceWrapper::GetKbdType() const { return mOverrideKeyboard ? eKbdType_ANSI : ::LMGetKbdType(); } -void TISInputSourceWrapper::ComputeInsertStringForCharCode(NSEvent* aNativeKeyEvent, - const WidgetKeyboardEvent& aKeyEvent, - const nsAString* aInsertString, - nsAString& aResult) { +void TISInputSourceWrapper::ComputeInsertStringForCharCode( + NSEvent* aNativeKeyEvent, const WidgetKeyboardEvent& aKeyEvent, + const nsAString* aInsertString, nsAString& aResult) { if (aInsertString) { // If the caller expects that the aInsertString will be input, we shouldn't // change it. @@ -946,7 +976,8 @@ void TISInputSourceWrapper::ComputeInsertStringForCharCode(NSEvent* aNativeKeyEv UInt32 nativeKeyCode = [aNativeKeyEvent keyCode]; if ((!aKeyEvent.IsMeta() && !aKeyEvent.IsControl() && IsOpenedIMEMode()) || ![[aNativeKeyEvent characters] length]) { - UInt32 state = nsCocoaUtils::ConvertToCarbonModifier([aNativeKeyEvent modifierFlags]); + UInt32 state = nsCocoaUtils::ConvertToCarbonModifier( + [aNativeKeyEvent modifierFlags]); uint32_t ch = TranslateToChar(nativeKeyCode, state, GetKbdType()); if (ch) { aResult = ch; @@ -959,20 +990,25 @@ void TISInputSourceWrapper::ComputeInsertStringForCharCode(NSEvent* aNativeKeyEv // If control key is pressed and the eventChars is a non-printable control // character, we should convert it to ASCII alphabet. - if (aKeyEvent.IsControl() && !aResult.IsEmpty() && aResult[0] <= char16_t(26)) { + if (aKeyEvent.IsControl() && !aResult.IsEmpty() && + aResult[0] <= char16_t(26)) { aResult = (aKeyEvent.IsShift() ^ aKeyEvent.IsCapsLocked()) ? static_cast(aResult[0] + ('A' - 1)) : static_cast(aResult[0] + ('a' - 1)); } // If Meta key is pressed, it may cause to switch the keyboard layout like // Arabic, Russian, Hebrew, Greek and Dvorak-QWERTY. - else if (aKeyEvent.IsMeta() && !(aKeyEvent.IsControl() || aKeyEvent.IsAlt())) { + else if (aKeyEvent.IsMeta() && + !(aKeyEvent.IsControl() || aKeyEvent.IsAlt())) { UInt32 kbType = GetKbdType(); - UInt32 numLockState = aKeyEvent.IsNumLocked() ? kEventKeyModifierNumLockMask : 0; + UInt32 numLockState = + aKeyEvent.IsNumLocked() ? kEventKeyModifierNumLockMask : 0; UInt32 capsLockState = aKeyEvent.IsCapsLocked() ? alphaLock : 0; UInt32 shiftState = aKeyEvent.IsShift() ? shiftKey : 0; - uint32_t uncmdedChar = TranslateToChar(nativeKeyCode, numLockState, kbType); - uint32_t cmdedChar = TranslateToChar(nativeKeyCode, cmdKey | numLockState, kbType); + uint32_t uncmdedChar = + TranslateToChar(nativeKeyCode, numLockState, kbType); + uint32_t cmdedChar = + TranslateToChar(nativeKeyCode, cmdKey | numLockState, kbType); // If we can make a good guess at the characters that the user would // expect this key combination to produce (with and without Shift) then // use those characters. This also corrects for CapsLock. @@ -980,15 +1016,17 @@ void TISInputSourceWrapper::ComputeInsertStringForCharCode(NSEvent* aNativeKeyEv if (uncmdedChar == cmdedChar) { // The characters produced with Command seem similar to those without // Command. - ch = TranslateToChar(nativeKeyCode, shiftState | capsLockState | numLockState, kbType); + ch = TranslateToChar(nativeKeyCode, + shiftState | capsLockState | numLockState, kbType); } else { TISInputSourceWrapper USLayout("com.apple.keylayout.US"); - uint32_t uncmdedUSChar = USLayout.TranslateToChar(nativeKeyCode, numLockState, kbType); + uint32_t uncmdedUSChar = + USLayout.TranslateToChar(nativeKeyCode, numLockState, kbType); // If it looks like characters from US keyboard layout when Command key // is pressed, we should compute a character in the layout. if (uncmdedUSChar == cmdedChar) { - ch = USLayout.TranslateToChar(nativeKeyCode, shiftState | capsLockState | numLockState, - kbType); + ch = USLayout.TranslateToChar( + nativeKeyCode, shiftState | capsLockState | numLockState, kbType); } } @@ -1008,8 +1046,10 @@ void TISInputSourceWrapper::ComputeInsertStringForCharCode(NSEvent* aNativeKeyEv } } -void TISInputSourceWrapper::InitKeyEvent(NSEvent* aNativeKeyEvent, WidgetKeyboardEvent& aKeyEvent, - bool aIsProcessedByIME, const nsAString* aInsertString) { +void TISInputSourceWrapper::InitKeyEvent(NSEvent* aNativeKeyEvent, + WidgetKeyboardEvent& aKeyEvent, + bool aIsProcessedByIME, + const nsAString* aInsertString) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; MOZ_ASSERT(!aIsProcessedByIME || aKeyEvent.mMessage != eKeyPress, @@ -1019,8 +1059,9 @@ void TISInputSourceWrapper::InitKeyEvent(NSEvent* aNativeKeyEvent, WidgetKeyboar ("%p TISInputSourceWrapper::InitKeyEvent, aNativeKeyEvent=%p, " "aKeyEvent.mMessage=%s, aProcessedByIME=%s, aInsertString=%p, " "IsOpenedIMEMode()=%s", - this, aNativeKeyEvent, GetGeckoKeyEventType(aKeyEvent), TrueOrFalse(aIsProcessedByIME), - aInsertString, TrueOrFalse(IsOpenedIMEMode()))); + this, aNativeKeyEvent, GetGeckoKeyEventType(aKeyEvent), + TrueOrFalse(aIsProcessedByIME), aInsertString, + TrueOrFalse(IsOpenedIMEMode()))); if (NS_WARN_IF(!aNativeKeyEvent)) { return; @@ -1042,11 +1083,13 @@ void TISInputSourceWrapper::InitKeyEvent(NSEvent* aNativeKeyEvent, WidgetKeyboar // So, if aIsProcessedByIME is true, it may be dead key. Let's check // if current key event is a dead key's keydown event. bool isProcessedByIME = - aIsProcessedByIME && !TISInputSourceWrapper::CurrentInputSource().IsDeadKey(aNativeKeyEvent); + aIsProcessedByIME && + !TISInputSourceWrapper::CurrentInputSource().IsDeadKey(aNativeKeyEvent); - aKeyEvent.mKeyCode = isProcessedByIME - ? NS_VK_PROCESSKEY - : ComputeGeckoKeyCode(nativeKeyCode, kbType, aKeyEvent.IsMeta()); + aKeyEvent.mKeyCode = + isProcessedByIME + ? NS_VK_PROCESSKEY + : ComputeGeckoKeyCode(nativeKeyCode, kbType, aKeyEvent.IsMeta()); switch (nativeKeyCode) { case kVK_Command: @@ -1090,8 +1133,9 @@ void TISInputSourceWrapper::InitKeyEvent(NSEvent* aNativeKeyEvent, WidgetKeyboar break; } - aKeyEvent.mIsRepeat = - ([aNativeKeyEvent type] == NSEventTypeKeyDown) ? [aNativeKeyEvent isARepeat] : false; + aKeyEvent.mIsRepeat = ([aNativeKeyEvent type] == NSEventTypeKeyDown) + ? [aNativeKeyEvent isARepeat] + : false; MOZ_LOG(gKeyLog, LogLevel::Info, ("%p TISInputSourceWrapper::InitKeyEvent, " @@ -1104,26 +1148,31 @@ void TISInputSourceWrapper::InitKeyEvent(NSEvent* aNativeKeyEvent, WidgetKeyboar } else if (IsPrintableKeyEvent(aNativeKeyEvent)) { aKeyEvent.mKeyNameIndex = KEY_NAME_INDEX_USE_STRING; // If insertText calls this method, let's use the string. - if (aInsertString && !aInsertString->IsEmpty() && !IsControlChar((*aInsertString)[0])) { + if (aInsertString && !aInsertString->IsEmpty() && + !IsControlChar((*aInsertString)[0])) { aKeyEvent.mKeyValue = *aInsertString; } // If meta key is pressed, the printable key layout may be switched from // non-ASCII capable layout to ASCII capable, or from Dvorak to QWERTY. // KeyboardEvent.key value should be the switched layout's character. else if (aKeyEvent.IsMeta()) { - nsCocoaUtils::GetStringForNSString([aNativeKeyEvent characters], aKeyEvent.mKeyValue); + nsCocoaUtils::GetStringForNSString([aNativeKeyEvent characters], + aKeyEvent.mKeyValue); } // If control key is pressed, some keys may produce printable character via // [aNativeKeyEvent characters]. Otherwise, translate input character of // the key without control key. else if (aKeyEvent.IsControl()) { - NSUInteger cocoaState = [aNativeKeyEvent modifierFlags] & ~NSEventModifierFlagControl; + NSUInteger cocoaState = + [aNativeKeyEvent modifierFlags] & ~NSEventModifierFlagControl; UInt32 carbonState = nsCocoaUtils::ConvertToCarbonModifier(cocoaState); if (IsDeadKey(nativeKeyCode, carbonState, kbType)) { aKeyEvent.mKeyNameIndex = KEY_NAME_INDEX_Dead; } else { - aKeyEvent.mKeyValue = TranslateToChar(nativeKeyCode, carbonState, kbType); - if (!aKeyEvent.mKeyValue.IsEmpty() && IsControlChar(aKeyEvent.mKeyValue[0])) { + aKeyEvent.mKeyValue = + TranslateToChar(nativeKeyCode, carbonState, kbType); + if (!aKeyEvent.mKeyValue.IsEmpty() && + IsControlChar(aKeyEvent.mKeyValue[0])) { // Don't expose control character to the web. aKeyEvent.mKeyValue.Truncate(); } @@ -1135,10 +1184,12 @@ void TISInputSourceWrapper::InitKeyEvent(NSEvent* aNativeKeyEvent, WidgetKeyboar // doesn't match with other platform's behavior. For the compatibility // with other platform's Gecko, we need to set a translated character. else if (IsOpenedIMEMode()) { - UInt32 state = nsCocoaUtils::ConvertToCarbonModifier([aNativeKeyEvent modifierFlags]); + UInt32 state = nsCocoaUtils::ConvertToCarbonModifier( + [aNativeKeyEvent modifierFlags]); aKeyEvent.mKeyValue = TranslateToChar(nativeKeyCode, state, kbType); } else { - nsCocoaUtils::GetStringForNSString([aNativeKeyEvent characters], aKeyEvent.mKeyValue); + nsCocoaUtils::GetStringForNSString([aNativeKeyEvent characters], + aKeyEvent.mKeyValue); // If the key value is empty, the event may be a dead key event. // If TranslateToChar() returns non-zero value, that means that // the key may input a character with different dead key state. @@ -1154,11 +1205,13 @@ void TISInputSourceWrapper::InitKeyEvent(NSEvent* aNativeKeyEvent, WidgetKeyboar // Last resort. If .key value becomes empty string, we should use // charactersIgnoringModifiers, if it's available. if (aKeyEvent.mKeyNameIndex == KEY_NAME_INDEX_USE_STRING && - (aKeyEvent.mKeyValue.IsEmpty() || IsControlChar(aKeyEvent.mKeyValue[0]))) { - nsCocoaUtils::GetStringForNSString([aNativeKeyEvent charactersIgnoringModifiers], - aKeyEvent.mKeyValue); + (aKeyEvent.mKeyValue.IsEmpty() || + IsControlChar(aKeyEvent.mKeyValue[0]))) { + nsCocoaUtils::GetStringForNSString( + [aNativeKeyEvent charactersIgnoringModifiers], aKeyEvent.mKeyValue); // But don't expose it if it's a control character. - if (!aKeyEvent.mKeyValue.IsEmpty() && IsControlChar(aKeyEvent.mKeyValue[0])) { + if (!aKeyEvent.mKeyValue.IsEmpty() && + IsControlChar(aKeyEvent.mKeyValue[0])) { aKeyEvent.mKeyValue.Truncate(); } } @@ -1173,16 +1226,16 @@ void TISInputSourceWrapper::InitKeyEvent(NSEvent* aNativeKeyEvent, WidgetKeyboar NS_OBJC_END_TRY_IGNORE_BLOCK } -void TISInputSourceWrapper::WillDispatchKeyboardEvent(NSEvent* aNativeKeyEvent, - const nsAString* aInsertString, - uint32_t aIndexOfKeypress, - WidgetKeyboardEvent& aKeyEvent) { +void TISInputSourceWrapper::WillDispatchKeyboardEvent( + NSEvent* aNativeKeyEvent, const nsAString* aInsertString, + uint32_t aIndexOfKeypress, WidgetKeyboardEvent& aKeyEvent) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - // Nothing to do here if the native key event is neither NSEventTypeKeyDown nor - // NSEventTypeKeyUp because accessing [aNativeKeyEvent characters] causes throwing - // an exception. - if ([aNativeKeyEvent type] != NSEventTypeKeyDown && [aNativeKeyEvent type] != NSEventTypeKeyUp) { + // Nothing to do here if the native key event is neither NSEventTypeKeyDown + // nor NSEventTypeKeyUp because accessing [aNativeKeyEvent characters] causes + // throwing an exception. + if ([aNativeKeyEvent type] != NSEventTypeKeyDown && + [aNativeKeyEvent type] != NSEventTypeKeyUp) { return; } @@ -1193,17 +1246,19 @@ void TISInputSourceWrapper::WillDispatchKeyboardEvent(NSEvent* aNativeKeyEvent, nsCocoaUtils::GetStringForNSString([aNativeKeyEvent characters], chars); NS_ConvertUTF16toUTF8 utf8Chars(chars); char16_t uniChar = static_cast(aKeyEvent.mCharCode); - MOZ_LOG(gKeyLog, LogLevel::Info, - ("%p TISInputSourceWrapper::WillDispatchKeyboardEvent, " - "aNativeKeyEvent=%p, aInsertString=%p (\"%s\"), " - "aIndexOfKeypress=%u, [aNativeKeyEvent characters]=\"%s\", " - "aKeyEvent={ mMessage=%s, mCharCode=0x%X(%s) }, kbType=0x%X, " - "IsOpenedIMEMode()=%s", - this, aNativeKeyEvent, aInsertString, - aInsertString ? GetCharacters(*aInsertString) : "", aIndexOfKeypress, - GetCharacters([aNativeKeyEvent characters]), GetGeckoKeyEventType(aKeyEvent), - aKeyEvent.mCharCode, uniChar ? NS_ConvertUTF16toUTF8(&uniChar, 1).get() : "", - static_cast(kbType), TrueOrFalse(IsOpenedIMEMode()))); + MOZ_LOG( + gKeyLog, LogLevel::Info, + ("%p TISInputSourceWrapper::WillDispatchKeyboardEvent, " + "aNativeKeyEvent=%p, aInsertString=%p (\"%s\"), " + "aIndexOfKeypress=%u, [aNativeKeyEvent characters]=\"%s\", " + "aKeyEvent={ mMessage=%s, mCharCode=0x%X(%s) }, kbType=0x%X, " + "IsOpenedIMEMode()=%s", + this, aNativeKeyEvent, aInsertString, + aInsertString ? GetCharacters(*aInsertString) : "", aIndexOfKeypress, + GetCharacters([aNativeKeyEvent characters]), + GetGeckoKeyEventType(aKeyEvent), aKeyEvent.mCharCode, + uniChar ? NS_ConvertUTF16toUTF8(&uniChar, 1).get() : "", + static_cast(kbType), TrueOrFalse(IsOpenedIMEMode()))); } nsAutoString insertStringForCharCode; @@ -1250,8 +1305,8 @@ void TISInputSourceWrapper::WillDispatchKeyboardEvent(NSEvent* aNativeKeyEvent, MOZ_LOG(gKeyLog, LogLevel::Info, ("%p TISInputSourceWrapper::WillDispatchKeyboardEvent, " "isRomanKeyboardLayout=%s, kbType=0x%X, key=0x%X", - this, TrueOrFalse(isRomanKeyboardLayout), static_cast(kbType), - static_cast(key))); + this, TrueOrFalse(isRomanKeyboardLayout), + static_cast(kbType), static_cast(key))); nsString str; @@ -1285,16 +1340,17 @@ void TISInputSourceWrapper::WillDispatchKeyboardEvent(NSEvent* aNativeKeyEvent, // we should append unshiftedChar and shiftedChar for handling the // normal characters. These are the characters that the user is most // likely to associate with this key. - if ((unshiftedChar || shiftedChar) && (!aKeyEvent.IsMeta() || !isDvorakQWERTY)) { + if ((unshiftedChar || shiftedChar) && + (!aKeyEvent.IsMeta() || !isDvorakQWERTY)) { AlternativeCharCode altCharCodes(unshiftedChar, shiftedChar); aKeyEvent.mAlternativeCharCodes.AppendElement(altCharCodes); } - MOZ_LOG( - gKeyLog, LogLevel::Info, - ("%p TISInputSourceWrapper::WillDispatchKeyboardEvent, " - "aKeyEvent.isMeta=%s, isDvorakQWERTY=%s, " - "unshiftedChar=U+%X, shiftedChar=U+%X", - this, OnOrOff(aKeyEvent.IsMeta()), TrueOrFalse(isDvorakQWERTY), unshiftedChar, shiftedChar)); + MOZ_LOG(gKeyLog, LogLevel::Info, + ("%p TISInputSourceWrapper::WillDispatchKeyboardEvent, " + "aKeyEvent.isMeta=%s, isDvorakQWERTY=%s, " + "unshiftedChar=U+%X, shiftedChar=U+%X", + this, OnOrOff(aKeyEvent.IsMeta()), TrueOrFalse(isDvorakQWERTY), + unshiftedChar, shiftedChar)); // Most keyboard layouts provide the same characters in the NSEvents // with Command+Shift as with Command. However, with Command+Shift we @@ -1310,7 +1366,8 @@ void TISInputSourceWrapper::WillDispatchKeyboardEvent(NSEvent* aNativeKeyEvent, // when Shift is pressed. However, in case there is a layout where the // character unique to Cmd+Shift is the character that the user expects, // we'll send it as an alternative char. - bool hasCmdShiftOnlyChar = cmdedChar != cmdedShiftChar && uncmdedShiftChar != cmdedShiftChar; + bool hasCmdShiftOnlyChar = + cmdedChar != cmdedShiftChar && uncmdedShiftChar != cmdedShiftChar; uint32_t originalCmdedShiftChar = cmdedShiftChar; // If we can make a good guess at the characters that the user would @@ -1370,15 +1427,17 @@ void TISInputSourceWrapper::WillDispatchKeyboardEvent(NSEvent* aNativeKeyEvent, NS_OBJC_END_TRY_IGNORE_BLOCK } -uint32_t TISInputSourceWrapper::ComputeGeckoKeyCode(UInt32 aNativeKeyCode, UInt32 aKbType, +uint32_t TISInputSourceWrapper::ComputeGeckoKeyCode(UInt32 aNativeKeyCode, + UInt32 aKbType, bool aCmdIsPressed) { MOZ_LOG( gKeyLog, LogLevel::Info, ("%p TISInputSourceWrapper::ComputeGeckoKeyCode, aNativeKeyCode=0x%X, " "aKbType=0x%X, aCmdIsPressed=%s, IsOpenedIMEMode()=%s, " "IsASCIICapable()=%s", - this, static_cast(aNativeKeyCode), static_cast(aKbType), - TrueOrFalse(aCmdIsPressed), TrueOrFalse(IsOpenedIMEMode()), TrueOrFalse(IsASCIICapable()))); + this, static_cast(aNativeKeyCode), + static_cast(aKbType), TrueOrFalse(aCmdIsPressed), + TrueOrFalse(IsOpenedIMEMode()), TrueOrFalse(IsASCIICapable()))); switch (aNativeKeyCode) { case kVK_Space: @@ -1582,7 +1641,8 @@ uint32_t TISInputSourceWrapper::ComputeGeckoKeyCode(UInt32 aNativeKeyCode, UInt3 TISInputSourceWrapper currentKeyboardLayout; currentKeyboardLayout.InitByCurrentASCIICapableKeyboardLayout(); NS_ENSURE_TRUE(mInputSource != currentKeyboardLayout.mInputSource, 0); - keyCode = currentKeyboardLayout.ComputeGeckoKeyCode(aNativeKeyCode, aKbType, aCmdIsPressed); + keyCode = currentKeyboardLayout.ComputeGeckoKeyCode(aNativeKeyCode, aKbType, + aCmdIsPressed); // We've returned 0 for long time if keyCode isn't for an alphabet keys or // a numeric key even in alternative ASCII capable keyboard layout because // we decided that we should avoid setting same keyCode value to 2 or @@ -1607,7 +1667,8 @@ uint32_t TISInputSourceWrapper::ComputeGeckoKeyCode(UInt32 aNativeKeyCode, UInt3 } // static -KeyNameIndex TISInputSourceWrapper::ComputeGeckoKeyNameIndex(UInt32 aNativeKeyCode) { +KeyNameIndex TISInputSourceWrapper::ComputeGeckoKeyNameIndex( + UInt32 aNativeKeyCode) { // NOTE: // When unsupported keys like Convert, Nonconvert of Japanese keyboard is // pressed: @@ -1630,8 +1691,8 @@ KeyNameIndex TISInputSourceWrapper::ComputeGeckoKeyNameIndex(UInt32 aNativeKeyCo } // static -CodeNameIndex TISInputSourceWrapper::ComputeGeckoCodeNameIndex(UInt32 aNativeKeyCode, - UInt32 aKbType) { +CodeNameIndex TISInputSourceWrapper::ComputeGeckoCodeNameIndex( + UInt32 aNativeKeyCode, UInt32 aKbType) { // macOS swaps native key code between Backquote key and IntlBackslash key // only when the keyboard type is ISO. Let's treat the key code after // swapping them here because Chromium does so only when computing .code @@ -1672,7 +1733,8 @@ NSUInteger TextInputHandler::sLastModifierState = 0; CFArrayRef TextInputHandler::CreateAllKeyboardLayoutList() { const void* keys[] = {kTISPropertyInputSourceType}; const void* values[] = {kTISTypeKeyboardLayout}; - CFDictionaryRef filter = ::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL); + CFDictionaryRef filter = + ::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL); NS_ASSERTION(filter, "failed to create the filter"); CFArrayRef list = ::TISCreateInputSourceList(filter, true); ::CFRelease(filter); @@ -1687,17 +1749,19 @@ void TextInputHandler::DebugPrintAllKeyboardLayouts() { CFIndex idx = ::CFArrayGetCount(list); TISInputSourceWrapper tis; for (CFIndex i = 0; i < idx; ++i) { - TISInputSourceRef inputSource = - static_cast(const_cast(::CFArrayGetValueAtIndex(list, i))); + TISInputSourceRef inputSource = static_cast( + const_cast(::CFArrayGetValueAtIndex(list, i))); tis.InitByTISInputSourceRef(inputSource); nsAutoString name, isid; tis.GetLocalizedName(name); tis.GetInputSourceID(isid); - MOZ_LOG( - gKeyLog, LogLevel::Info, - (" %s\t<%s>%s%s\n", NS_ConvertUTF16toUTF8(name).get(), NS_ConvertUTF16toUTF8(isid).get(), - tis.IsASCIICapable() ? "" : "\t(Isn't ASCII capable)", - tis.IsKeyboardLayout() && tis.GetUCKeyboardLayout() ? "" : "\t(uchr is NOT AVAILABLE)")); + MOZ_LOG(gKeyLog, LogLevel::Info, + (" %s\t<%s>%s%s\n", NS_ConvertUTF16toUTF8(name).get(), + NS_ConvertUTF16toUTF8(isid).get(), + tis.IsASCIICapable() ? "" : "\t(Isn't ASCII capable)", + tis.IsKeyboardLayout() && tis.GetUCKeyboardLayout() + ? "" + : "\t(uchr is NOT AVAILABLE)")); } ::CFRelease(list); } @@ -1711,7 +1775,8 @@ void TextInputHandler::DebugPrintAllKeyboardLayouts() { * ******************************************************************************/ -TextInputHandler::TextInputHandler(nsChildView* aWidget, NSView* aNativeView) +TextInputHandler::TextInputHandler(nsChildView* aWidget, + NSView* aNativeView) : IMEInputHandler(aWidget, aNativeView) { EnsureToLogAllKeyboardLayoutsAndIMEs(); [mView installTextInputHandler:this]; @@ -1719,13 +1784,15 @@ TextInputHandler::TextInputHandler(nsChildView* aWidget, NSView* aNativ TextInputHandler::~TextInputHandler() { [mView uninstallTextInputHandler]; } -bool TextInputHandler::HandleKeyDownEvent(NSEvent* aNativeEvent, uint32_t aUniqueId) { +bool TextInputHandler::HandleKeyDownEvent(NSEvent* aNativeEvent, + uint32_t aUniqueId) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; if (Destroyed()) { - MOZ_LOG_KEY_OR_IME(LogLevel::Info, ("%p TextInputHandler::HandleKeyDownEvent, " - "widget has been already destroyed", - this)); + MOZ_LOG_KEY_OR_IME(LogLevel::Info, + ("%p TextInputHandler::HandleKeyDownEvent, " + "widget has been already destroyed", + this)); return false; } @@ -1736,8 +1803,9 @@ bool TextInputHandler::HandleKeyDownEvent(NSEvent* aNativeEvent, uint32_t aUniqu ("%p TextInputHandler::HandleKeyDownEvent, aNativeEvent=%p, " "type=%s, keyCode=%u (0x%X), modifierFlags=0x%lX, characters=\"%s\", " "charactersIgnoringModifiers=\"%s\"", - this, aNativeEvent, GetNativeKeyEventType(aNativeEvent), [aNativeEvent keyCode], - [aNativeEvent keyCode], static_cast([aNativeEvent modifierFlags]), + this, aNativeEvent, GetNativeKeyEventType(aNativeEvent), + [aNativeEvent keyCode], [aNativeEvent keyCode], + static_cast([aNativeEvent modifierFlags]), GetCharacters([aNativeEvent characters]), GetCharacters([aNativeEvent charactersIgnoringModifiers]))); @@ -1763,7 +1831,8 @@ bool TextInputHandler::HandleKeyDownEvent(NSEvent* aNativeEvent, uint32_t aUniqu // such case. if (IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(true)) { MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::HandleKeyDownEvent, eKeyDown caused focus move or " + ("%p TextInputHandler::HandleKeyDownEvent, eKeyDown " + "caused focus move or " "something and canceling the composition", this)); return false; @@ -1776,26 +1845,31 @@ bool TextInputHandler::HandleKeyDownEvent(NSEvent* aNativeEvent, uint32_t aUniqu // for example, a character is inputted twice during a composition in e10s // mode. if (IsIMEEnabled() || IsASCIICapableOnly()) { - MOZ_LOG_KEY_OR_IME( - LogLevel::Info, - ("%p TextInputHandler::HandleKeyDownEvent, calling interpretKeyEvents", this)); + MOZ_LOG_KEY_OR_IME(LogLevel::Info, + ("%p TextInputHandler::HandleKeyDownEvent, calling " + "interpretKeyEvents", + this)); [mView interpretKeyEvents:[NSArray arrayWithObject:aNativeEvent]]; interpretKeyEventsCalled = true; MOZ_LOG_KEY_OR_IME( LogLevel::Info, - ("%p TextInputHandler::HandleKeyDownEvent, called interpretKeyEvents", this)); + ("%p TextInputHandler::HandleKeyDownEvent, called interpretKeyEvents", + this)); } if (Destroyed()) { - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::HandleKeyDownEvent, widget was destroyed", this)); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandler::HandleKeyDownEvent, widget was destroyed", + this)); return currentKeyEvent->IsDefaultPrevented(); } - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::HandleKeyDownEvent, wasComposing=%s, " - "IsIMEComposing()=%s", - this, TrueOrFalse(wasComposing), TrueOrFalse(IsIMEComposing()))); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandler::HandleKeyDownEvent, wasComposing=%s, " + "IsIMEComposing()=%s", + this, TrueOrFalse(wasComposing), TrueOrFalse(IsIMEComposing()))); if (currentKeyEvent->CanDispatchKeyDownEvent()) { // Dispatch eKeyDown event if nobody has dispatched it yet. @@ -1809,25 +1883,30 @@ bool TextInputHandler::HandleKeyDownEvent(NSEvent* aNativeEvent, uint32_t aUniqu // not updated. So, let's mark eKeyDown event as "processed by IME" // when there is composition string. This is same as Chrome. MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::HandleKeyDownEvent, trying to dispatch eKeyDown " + ("%p TextInputHandler::HandleKeyDownEvent, trying to " + "dispatch eKeyDown " "event since it's not yet dispatched", this)); if (!MaybeDispatchCurrentKeydownEvent(IsIMEComposing())) { return true; // treat the eKeydDown event as consumed. } - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::HandleKeyDownEvent, eKeyDown event has been " - "dispatched", - this)); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandler::HandleKeyDownEvent, eKeyDown event has been " + "dispatched", + this)); } - if (currentKeyEvent->CanDispatchKeyPressEvent() && !wasComposing && !IsIMEComposing()) { + if (currentKeyEvent->CanDispatchKeyPressEvent() && !wasComposing && + !IsIMEComposing()) { nsresult rv = mDispatcher->BeginNativeInputTransaction(); if (NS_WARN_IF(NS_FAILED(rv))) { - MOZ_LOG_KEY_OR_IME(LogLevel::Error, ("%p TextInputHandler::HandleKeyDownEvent, " - "FAILED, due to BeginNativeInputTransaction() failure " - "at dispatching keypress", - this)); + MOZ_LOG_KEY_OR_IME( + LogLevel::Error, + ("%p TextInputHandler::HandleKeyDownEvent, " + "FAILED, due to BeginNativeInputTransaction() failure " + "at dispatching keypress", + this)); return false; } @@ -1845,33 +1924,39 @@ bool TextInputHandler::HandleKeyDownEvent(NSEvent* aNativeEvent, uint32_t aUniqu // dispatch keypress event at that time. Note that the command may have // been a converted or generated action by IME. Then, we shouldn't do // our default action for this key. - if (!(interpretKeyEventsCalled && IsNormalCharInputtingEvent(aNativeEvent))) { - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::HandleKeyDownEvent, trying to dispatch " - "eKeyPress event since it's not yet dispatched", - this)); + if (!(interpretKeyEventsCalled && + IsNormalCharInputtingEvent(aNativeEvent))) { + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandler::HandleKeyDownEvent, trying to dispatch " + "eKeyPress event since it's not yet dispatched", + this)); nsEventStatus status = nsEventStatus_eIgnore; currentKeyEvent->mKeyPressDispatched = - mDispatcher->MaybeDispatchKeypressEvents(keypressEvent, status, currentKeyEvent); - currentKeyEvent->mKeyPressHandled = (status == nsEventStatus_eConsumeNoDefault); + mDispatcher->MaybeDispatchKeypressEvents(keypressEvent, status, + currentKeyEvent); + currentKeyEvent->mKeyPressHandled = + (status == nsEventStatus_eConsumeNoDefault); currentKeyEvent->mKeyPressDispatched = true; - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::HandleKeyDownEvent, eKeyPress event has been " - "dispatched", - this)); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandler::HandleKeyDownEvent, eKeyPress event has been " + "dispatched", + this)); } } // Note: mWidget might have become null here. Don't count on it from here on. - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::HandleKeyDownEvent, " - "keydown handled=%s, keypress handled=%s, causedOtherKeyEvents=%s, " - "compositionDispatched=%s", - this, TrueOrFalse(currentKeyEvent->mKeyDownHandled), - TrueOrFalse(currentKeyEvent->mKeyPressHandled), - TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents), - TrueOrFalse(currentKeyEvent->mCompositionDispatched))); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandler::HandleKeyDownEvent, " + "keydown handled=%s, keypress handled=%s, causedOtherKeyEvents=%s, " + "compositionDispatched=%s", + this, TrueOrFalse(currentKeyEvent->mKeyDownHandled), + TrueOrFalse(currentKeyEvent->mKeyPressHandled), + TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents), + TrueOrFalse(currentKeyEvent->mCompositionDispatched))); // Insert empty line to the log for easier to read. MOZ_LOG_KEY_OR_IME(LogLevel::Info, ("")); return currentKeyEvent->IsDefaultPrevented(); @@ -1888,23 +1973,27 @@ void TextInputHandler::HandleKeyUpEvent(NSEvent* aNativeEvent) { "type=%s, keyCode=%u (0x%X), modifierFlags=0x%lX, characters=\"%s\", " "charactersIgnoringModifiers=\"%s\", " "IsIMEComposing()=%s", - this, aNativeEvent, GetNativeKeyEventType(aNativeEvent), [aNativeEvent keyCode], - [aNativeEvent keyCode], static_cast([aNativeEvent modifierFlags]), + this, aNativeEvent, GetNativeKeyEventType(aNativeEvent), + [aNativeEvent keyCode], [aNativeEvent keyCode], + static_cast([aNativeEvent modifierFlags]), GetCharacters([aNativeEvent characters]), - GetCharacters([aNativeEvent charactersIgnoringModifiers]), TrueOrFalse(IsIMEComposing()))); + GetCharacters([aNativeEvent charactersIgnoringModifiers]), + TrueOrFalse(IsIMEComposing()))); if (Destroyed()) { - MOZ_LOG_KEY_OR_IME(LogLevel::Info, ("%p TextInputHandler::HandleKeyUpEvent, " - "widget has been already destroyed", - this)); + MOZ_LOG_KEY_OR_IME(LogLevel::Info, + ("%p TextInputHandler::HandleKeyUpEvent, " + "widget has been already destroyed", + this)); return; } nsresult rv = mDispatcher->BeginNativeInputTransaction(); if (NS_WARN_IF(NS_FAILED(rv))) { - MOZ_LOG_KEY_OR_IME(LogLevel::Error, ("%p TextInputHandler::HandleKeyUpEvent, " - "FAILED, due to BeginNativeInputTransaction() failure", - this)); + MOZ_LOG_KEY_OR_IME(LogLevel::Error, + ("%p TextInputHandler::HandleKeyUpEvent, " + "FAILED, due to BeginNativeInputTransaction() failure", + this)); return; } @@ -1915,7 +2004,8 @@ void TextInputHandler::HandleKeyUpEvent(NSEvent* aNativeEvent) { KeyEventState currentKeyEvent(aNativeEvent); nsEventStatus status = nsEventStatus_eIgnore; - mDispatcher->DispatchKeyboardEvent(eKeyUp, keyupEvent, status, ¤tKeyEvent); + mDispatcher->DispatchKeyboardEvent(eKeyUp, keyupEvent, status, + ¤tKeyEvent); NS_OBJC_END_TRY_IGNORE_BLOCK; } @@ -1924,9 +2014,10 @@ void TextInputHandler::HandleFlagsChanged(NSEvent* aNativeEvent) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; if (Destroyed()) { - MOZ_LOG_KEY_OR_IME(LogLevel::Info, ("%p TextInputHandler::HandleFlagsChanged, " - "widget has been already destroyed", - this)); + MOZ_LOG_KEY_OR_IME(LogLevel::Info, + ("%p TextInputHandler::HandleFlagsChanged, " + "widget has been already destroyed", + this)); return; } @@ -1939,9 +2030,11 @@ void TextInputHandler::HandleFlagsChanged(NSEvent* aNativeEvent) { "type=%s, keyCode=%s (0x%X), modifierFlags=0x%08lX, " "sLastModifierState=0x%08lX, IsIMEComposing()=%s", this, aNativeEvent, GetNativeKeyEventType(aNativeEvent), - GetKeyNameForNativeKeyCode([aNativeEvent keyCode]), [aNativeEvent keyCode], + GetKeyNameForNativeKeyCode([aNativeEvent keyCode]), + [aNativeEvent keyCode], static_cast([aNativeEvent modifierFlags]), - static_cast(sLastModifierState), TrueOrFalse(IsIMEComposing()))); + static_cast(sLastModifierState), + TrueOrFalse(IsIMEComposing()))); MOZ_ASSERT([aNativeEvent type] == NSEventTypeFlagsChanged); @@ -1990,16 +2083,19 @@ void TextInputHandler::HandleFlagsChanged(NSEvent* aNativeEvent) { DispatchKeyEventForFlagsChanged(aNativeEvent, isKeyDown); // XXX Some applications might send the event with incorrect device- // dependent flags. - if (isKeyDown && ((diff & ~NSEventModifierFlagDeviceIndependentFlagsMask) != 0)) { + if (isKeyDown && + ((diff & ~NSEventModifierFlagDeviceIndependentFlagsMask) != 0)) { unsigned short keyCode = [aNativeEvent keyCode]; - const ModifierKey* modifierKey = GetModifierKeyForDeviceDependentFlags(diff); + const ModifierKey* modifierKey = + GetModifierKeyForDeviceDependentFlags(diff); if (modifierKey && modifierKey->keyCode != keyCode) { // Although, we're not sure the actual cause of this case, the stored // modifier information and the latest key event information may be // mismatched. Then, let's reset the stored information. - // NOTE: If this happens, it may fail to handle NSEventTypeFlagsChanged event - // in the default case (below). However, it's the rare case handler - // and this case occurs rarely. So, we can ignore the edge case bug. + // NOTE: If this happens, it may fail to handle + // NSEventTypeFlagsChanged event in the default case (below). However, + // it's the rare case handler and this case occurs rarely. So, we can + // ignore the edge case bug. NS_WARNING("Resetting stored modifier key information"); mModifierKeys.Clear(); modifierKey = nullptr; @@ -2049,9 +2145,9 @@ void TextInputHandler::HandleFlagsChanged(NSEvent* aNativeEvent) { break; case NSEventModifierFlagNumericPad: - // NSEventModifierFlagNumericPad is fired by VNC a lot. But not all of - // these events can really be Clear key events, so we just ignore - // them. + // NSEventModifierFlagNumericPad is fired by VNC a lot. But not + // all of these events can really be Clear key events, so we just + // ignore them. continue; case NSEventModifierFlagHelp: @@ -2064,11 +2160,13 @@ void TextInputHandler::HandleFlagsChanged(NSEvent* aNativeEvent) { // VNC for example) with a zero keyCode. continue; - // These cases (NSEventModifierFlagShift, NSEventModifierFlagControl, - // NSEventModifierFlagOption and NSEventModifierFlagCommand) should be handled by the - // other branch of the if statement, below (which handles device dependent flags). - // However, some applications (like VNC) can send key events without - // any device dependent flags, so we handle them here instead. + // These cases (NSEventModifierFlagShift, + // NSEventModifierFlagControl, NSEventModifierFlagOption and + // NSEventModifierFlagCommand) should be handled by the other branch + // of the if statement, below (which handles device dependent + // flags). However, some applications (like VNC) can send key events + // without any device dependent flags, so we handle them here + // instead. case NSEventModifierFlagShift: keyCode = (modifiers & 0x0004) ? kVK_RightShift : kVK_Shift; break; @@ -2086,7 +2184,8 @@ void TextInputHandler::HandleFlagsChanged(NSEvent* aNativeEvent) { continue; } } else { - const ModifierKey* modifierKey = GetModifierKeyForDeviceDependentFlags(flag); + const ModifierKey* modifierKey = + GetModifierKeyForDeviceDependentFlags(flag); if (!modifierKey) { // See the note above (in the other branch of the if statement) // about the NSEventModifierFlagShift, NSEventModifierFlagControl, @@ -2100,57 +2199,73 @@ void TextInputHandler::HandleFlagsChanged(NSEvent* aNativeEvent) { modifiers &= ~flag; switch (keyCode) { case kVK_Shift: { - const ModifierKey* modifierKey = GetModifierKeyForNativeKeyCode(kVK_RightShift); - if (!modifierKey || !(modifiers & modifierKey->GetDeviceDependentFlags())) { + const ModifierKey* modifierKey = + GetModifierKeyForNativeKeyCode(kVK_RightShift); + if (!modifierKey || + !(modifiers & modifierKey->GetDeviceDependentFlags())) { modifiers &= ~NSEventModifierFlagShift; } break; } case kVK_RightShift: { - const ModifierKey* modifierKey = GetModifierKeyForNativeKeyCode(kVK_Shift); - if (!modifierKey || !(modifiers & modifierKey->GetDeviceDependentFlags())) { + const ModifierKey* modifierKey = + GetModifierKeyForNativeKeyCode(kVK_Shift); + if (!modifierKey || + !(modifiers & modifierKey->GetDeviceDependentFlags())) { modifiers &= ~NSEventModifierFlagShift; } break; } case kVK_Command: { - const ModifierKey* modifierKey = GetModifierKeyForNativeKeyCode(kVK_RightCommand); - if (!modifierKey || !(modifiers & modifierKey->GetDeviceDependentFlags())) { + const ModifierKey* modifierKey = + GetModifierKeyForNativeKeyCode(kVK_RightCommand); + if (!modifierKey || + !(modifiers & modifierKey->GetDeviceDependentFlags())) { modifiers &= ~NSEventModifierFlagCommand; } break; } case kVK_RightCommand: { - const ModifierKey* modifierKey = GetModifierKeyForNativeKeyCode(kVK_Command); - if (!modifierKey || !(modifiers & modifierKey->GetDeviceDependentFlags())) { + const ModifierKey* modifierKey = + GetModifierKeyForNativeKeyCode(kVK_Command); + if (!modifierKey || + !(modifiers & modifierKey->GetDeviceDependentFlags())) { modifiers &= ~NSEventModifierFlagCommand; } break; } case kVK_Control: { - const ModifierKey* modifierKey = GetModifierKeyForNativeKeyCode(kVK_RightControl); - if (!modifierKey || !(modifiers & modifierKey->GetDeviceDependentFlags())) { + const ModifierKey* modifierKey = + GetModifierKeyForNativeKeyCode(kVK_RightControl); + if (!modifierKey || + !(modifiers & modifierKey->GetDeviceDependentFlags())) { modifiers &= ~NSEventModifierFlagControl; } break; } case kVK_RightControl: { - const ModifierKey* modifierKey = GetModifierKeyForNativeKeyCode(kVK_Control); - if (!modifierKey || !(modifiers & modifierKey->GetDeviceDependentFlags())) { + const ModifierKey* modifierKey = + GetModifierKeyForNativeKeyCode(kVK_Control); + if (!modifierKey || + !(modifiers & modifierKey->GetDeviceDependentFlags())) { modifiers &= ~NSEventModifierFlagControl; } break; } case kVK_Option: { - const ModifierKey* modifierKey = GetModifierKeyForNativeKeyCode(kVK_RightOption); - if (!modifierKey || !(modifiers & modifierKey->GetDeviceDependentFlags())) { + const ModifierKey* modifierKey = + GetModifierKeyForNativeKeyCode(kVK_RightOption); + if (!modifierKey || + !(modifiers & modifierKey->GetDeviceDependentFlags())) { modifiers &= ~NSEventModifierFlagOption; } break; } case kVK_RightOption: { - const ModifierKey* modifierKey = GetModifierKeyForNativeKeyCode(kVK_Option); - if (!modifierKey || !(modifiers & modifierKey->GetDeviceDependentFlags())) { + const ModifierKey* modifierKey = + GetModifierKeyForNativeKeyCode(kVK_Option); + if (!modifierKey || + !(modifiers & modifierKey->GetDeviceDependentFlags())) { modifiers &= ~NSEventModifierFlagOption; } break; @@ -2170,16 +2285,17 @@ void TextInputHandler::HandleFlagsChanged(NSEvent* aNativeEvent) { } dispatchedKeyCodes.AppendElement(keyCode); - NSEvent* event = [NSEvent keyEventWithType:NSEventTypeFlagsChanged - location:[aNativeEvent locationInWindow] - modifierFlags:modifiers - timestamp:[aNativeEvent timestamp] - windowNumber:[aNativeEvent windowNumber] - context:nil - characters:@"" - charactersIgnoringModifiers:@"" - isARepeat:NO - keyCode:keyCode]; + NSEvent* event = + [NSEvent keyEventWithType:NSEventTypeFlagsChanged + location:[aNativeEvent locationInWindow] + modifierFlags:modifiers + timestamp:[aNativeEvent timestamp] + windowNumber:[aNativeEvent windowNumber] + context:nil + characters:@"" + charactersIgnoringModifiers:@"" + isARepeat:NO + keyCode:keyCode]; DispatchKeyEventForFlagsChanged(event, dispatchKeyDown); if (Destroyed()) { break; @@ -2201,7 +2317,8 @@ void TextInputHandler::HandleFlagsChanged(NSEvent* aNativeEvent) { NS_OBJC_END_TRY_IGNORE_BLOCK; } -const TextInputHandler::ModifierKey* TextInputHandler::GetModifierKeyForNativeKeyCode( +const TextInputHandler::ModifierKey* +TextInputHandler::GetModifierKeyForNativeKeyCode( unsigned short aKeyCode) const { for (ModifierKeyArray::index_type i = 0; i < mModifierKeys.Length(); ++i) { if (mModifierKeys[i].keyCode == aKeyCode) { @@ -2211,7 +2328,8 @@ const TextInputHandler::ModifierKey* TextInputHandler::GetModifierKeyForNativeKe return nullptr; } -const TextInputHandler::ModifierKey* TextInputHandler::GetModifierKeyForDeviceDependentFlags( +const TextInputHandler::ModifierKey* +TextInputHandler::GetModifierKeyForDeviceDependentFlags( NSUInteger aFlags) const { for (ModifierKeyArray::index_type i = 0; i < mModifierKeys.Length(); ++i) { if (mModifierKeys[i].GetDeviceDependentFlags() == @@ -2230,12 +2348,14 @@ void TextInputHandler::DispatchKeyEventForFlagsChanged(NSEvent* aNativeEvent, return; } - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::DispatchKeyEventForFlagsChanged, aNativeEvent=%p, " - "type=%s, keyCode=%s (0x%X), aDispatchKeyDown=%s, IsIMEComposing()=%s", - this, aNativeEvent, GetNativeKeyEventType(aNativeEvent), - GetKeyNameForNativeKeyCode([aNativeEvent keyCode]), [aNativeEvent keyCode], - TrueOrFalse(aDispatchKeyDown), TrueOrFalse(IsIMEComposing()))); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandler::DispatchKeyEventForFlagsChanged, aNativeEvent=%p, " + "type=%s, keyCode=%s (0x%X), aDispatchKeyDown=%s, IsIMEComposing()=%s", + this, aNativeEvent, GetNativeKeyEventType(aNativeEvent), + GetKeyNameForNativeKeyCode([aNativeEvent keyCode]), + [aNativeEvent keyCode], TrueOrFalse(aDispatchKeyDown), + TrueOrFalse(IsIMEComposing()))); if ([aNativeEvent type] != NSEventTypeFlagsChanged) { return; @@ -2243,9 +2363,11 @@ void TextInputHandler::DispatchKeyEventForFlagsChanged(NSEvent* aNativeEvent, nsresult rv = mDispatcher->BeginNativeInputTransaction(); if (NS_WARN_IF(NS_FAILED(rv))) { - MOZ_LOG_KEY_OR_IME(LogLevel::Error, ("%p TextInputHandler::DispatchKeyEventForFlagsChanged, " - "FAILED, due to BeginNativeInputTransaction() failure", - this)); + MOZ_LOG_KEY_OR_IME( + LogLevel::Error, + ("%p TextInputHandler::DispatchKeyEventForFlagsChanged, " + "FAILED, due to BeginNativeInputTransaction() failure", + this)); return; } @@ -2259,12 +2381,14 @@ void TextInputHandler::DispatchKeyEventForFlagsChanged(NSEvent* aNativeEvent, KeyEventState currentKeyEvent(aNativeEvent); nsEventStatus status = nsEventStatus_eIgnore; - mDispatcher->DispatchKeyboardEvent(message, keyEvent, status, ¤tKeyEvent); + mDispatcher->DispatchKeyboardEvent(message, keyEvent, status, + ¤tKeyEvent); NS_OBJC_END_TRY_IGNORE_BLOCK; } -void TextInputHandler::InsertText(NSAttributedString* aAttrString, NSRange* aReplacementRange) { +void TextInputHandler::InsertText(NSAttributedString* aAttrString, + NSRange* aReplacementRange) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; if (Destroyed()) { @@ -2282,14 +2406,21 @@ void TextInputHandler::InsertText(NSAttributedString* aAttrString, NSRange* aRep "keydownHandled=%s, keypressDispatched=%s, " "causedOtherKeyEvents=%s, compositionDispatched=%s", this, GetCharacters([aAttrString string]), aReplacementRange, - static_cast(aReplacementRange ? aReplacementRange->location : 0), - static_cast(aReplacementRange ? aReplacementRange->length : 0), - TrueOrFalse(IsIMEComposing()), currentKeyEvent ? currentKeyEvent->mKeyEvent : nullptr, - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownDispatched) : "N/A", + static_cast( + aReplacementRange ? aReplacementRange->location : 0), + static_cast(aReplacementRange ? aReplacementRange->length + : 0), + TrueOrFalse(IsIMEComposing()), + currentKeyEvent ? currentKeyEvent->mKeyEvent : nullptr, + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownDispatched) + : "N/A", currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownHandled) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCompositionDispatched) : "N/A")); + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched) + : "N/A", + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents) + : "N/A", + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCompositionDispatched) + : "N/A")); InputContext context = mWidget->GetInputContext(); bool isEditable = (context.mIMEState.mEnabled == IMEEnabled::Enabled || @@ -2341,24 +2472,27 @@ void TextInputHandler::InsertText(NSAttributedString* aAttrString, NSRange* aRep // XXX Should we mark this eKeyDown event as "processed by IME"? RefPtr kungFuDeathGrip(this); if (!IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(false)) { - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::InsertText, eKeyDown caused focus move or " - "something and canceling the composition", - this)); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandler::InsertText, eKeyDown caused focus move or " + "something and canceling the composition", + this)); return; } // Delete the selected range. - WidgetContentCommandEvent deleteCommandEvent(true, eContentCommandDelete, mWidget); + WidgetContentCommandEvent deleteCommandEvent(true, eContentCommandDelete, + mWidget); DispatchEvent(deleteCommandEvent); NS_ENSURE_TRUE_VOID(deleteCommandEvent.mSucceeded); // Be aware! The widget might be destroyed here. return; } - bool isReplacingSpecifiedRange = isEditable && aReplacementRange && - aReplacementRange->location != NSNotFound && - !NSEqualRanges(selectedRange, *aReplacementRange); + bool isReplacingSpecifiedRange = + isEditable && aReplacementRange && + aReplacementRange->location != NSNotFound && + !NSEqualRanges(selectedRange, *aReplacementRange); // If this is not caused by pressing a key, there is a composition or // replacing a range which is different from current selection, let's @@ -2368,8 +2502,8 @@ void TextInputHandler::InsertText(NSAttributedString* aAttrString, NSRange* aRep // XXX When InsertText() is called multiple times, Chromium dispatches // only one composition event. So, we need to store InsertText() // calls and flush later. - if (!currentKeyEvent || currentKeyEvent->mCompositionDispatched || IsIMEComposing() || - isReplacingSpecifiedRange) { + if (!currentKeyEvent || currentKeyEvent->mCompositionDispatched || + IsIMEComposing() || isReplacingSpecifiedRange) { InsertTextAsCommittingComposition(aAttrString, aReplacementRange); if (currentKeyEvent) { currentKeyEvent->mCompositionDispatched = true; @@ -2399,10 +2533,11 @@ void TextInputHandler::InsertText(NSAttributedString* aAttrString, NSRange* aRep // Let's dispatch eKeyDown event now. RefPtr kungFuDeathGrip(this); if (!MaybeDispatchCurrentKeydownEvent(false)) { - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::InsertText, eKeyDown caused focus move or " - "something and canceling the composition", - this)); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandler::InsertText, eKeyDown caused focus move or " + "something and canceling the composition", + this)); return; } @@ -2410,16 +2545,17 @@ void TextInputHandler::InsertText(NSAttributedString* aAttrString, NSRange* aRep RefPtr widget(mWidget); nsresult rv = mDispatcher->BeginNativeInputTransaction(); if (NS_WARN_IF(NS_FAILED(rv))) { - MOZ_LOG_KEY_OR_IME(LogLevel::Error, ("%p TextInputHandler::InsertText, " - "FAILED, due to BeginNativeInputTransaction() failure", - this)); + MOZ_LOG_KEY_OR_IME(LogLevel::Error, + ("%p TextInputHandler::InsertText, " + "FAILED, due to BeginNativeInputTransaction() failure", + this)); return; } - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::InsertText, " - "maybe dispatches eKeyPress event without control, alt and meta modifiers", - this)); + MOZ_LOG_KEY_OR_IME(LogLevel::Info, ("%p TextInputHandler::InsertText, " + "maybe dispatches eKeyPress event " + "without control, alt and meta modifiers", + this)); // Dispatch keypress event with char instead of compositionchange event WidgetKeyboardEvent keypressEvent(true, eKeyPress, widget); @@ -2446,8 +2582,8 @@ void TextInputHandler::InsertText(NSAttributedString* aAttrString, NSRange* aRep // If mCurrentKeyEvent.mKeyEvent is null, the text should be inputted as // composition events. nsEventStatus status = nsEventStatus_eIgnore; - bool keyPressDispatched = - mDispatcher->MaybeDispatchKeypressEvents(keypressEvent, status, currentKeyEvent); + bool keyPressDispatched = mDispatcher->MaybeDispatchKeypressEvents( + keypressEvent, status, currentKeyEvent); bool keyPressHandled = (status == nsEventStatus_eConsumeNoDefault); // Note: mWidget might have become null here. Don't count on it from here on. @@ -2478,9 +2614,12 @@ bool TextInputHandler::HandleCommand(Command aCommand) { this, ToChar(aCommand), TrueOrFalse(IsIMEComposing()), currentKeyEvent ? currentKeyEvent->mKeyEvent : nullptr, currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownHandled) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCompositionDispatched) : "N/A")); + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched) + : "N/A", + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents) + : "N/A", + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCompositionDispatched) + : "N/A")); // The command shouldn't be handled, let's ignore it. if (currentKeyEvent && !currentKeyEvent->CanHandleCommand()) { @@ -2493,10 +2632,11 @@ bool TextInputHandler::HandleCommand(Command aCommand) { // TextInputHandler::HandleKeyDownEvent(). RefPtr kungFuDeathGrip(this); if (!IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(false)) { - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::SetMarkedText, eKeyDown caused focus move or " - "something and canceling the composition", - this)); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandler::SetMarkedText, eKeyDown caused focus move or " + "something and canceling the composition", + this)); return false; } @@ -2512,8 +2652,10 @@ bool TextInputHandler::HandleCommand(Command aCommand) { // doesn't treat "\n" in composition string as a line break unless // the whitespace is treated as pre (see bug 1350541). In strictly // speaking, we should dispatch keypress event as-is if it's handling - // NSEventTypeKeyDown event or should insert it with committing composition. - NSAttributedString* lineBreaker = [[NSAttributedString alloc] initWithString:@"\n"]; + // NSEventTypeKeyDown event or should insert it with committing + // composition. + NSAttributedString* lineBreaker = + [[NSAttributedString alloc] initWithString:@"\n"]; InsertTextAsCommittingComposition(lineBreaker, nullptr); if (currentKeyEvent) { currentKeyEvent->mCompositionDispatched = true; @@ -2573,9 +2715,10 @@ bool TextInputHandler::HandleCommand(Command aCommand) { RefPtr widget(mWidget); nsresult rv = mDispatcher->BeginNativeInputTransaction(); if (NS_WARN_IF(NS_FAILED(rv))) { - MOZ_LOG_KEY_OR_IME(LogLevel::Error, ("%p, TextInputHandler::HandleCommand, " - "FAILED, due to BeginNativeInputTransaction() failure", - this)); + MOZ_LOG_KEY_OR_IME(LogLevel::Error, + ("%p, TextInputHandler::HandleCommand, " + "FAILED, due to BeginNativeInputTransaction() failure", + this)); return false; } @@ -2588,7 +2731,8 @@ bool TextInputHandler::HandleCommand(Command aCommand) { // events nor other key events, we should expose actual modifier state. // Otherwise, we should adjust Control, Option and Command state since // editor may behave differently if some of them are active. - bool dispatchFakeKeyPress = !(currentKeyEvent && currentKeyEvent->IsProperKeyEvent(aCommand)); + bool dispatchFakeKeyPress = + !(currentKeyEvent && currentKeyEvent->IsProperKeyEvent(aCommand)); WidgetKeyboardEvent keydownEvent(true, eKeyDown, widget); WidgetKeyboardEvent keypressEvent(true, eKeyPress, widget); @@ -2605,8 +2749,9 @@ bool TextInputHandler::HandleCommand(Command aCommand) { // this command. NSEvent* keyEvent = currentKeyEvent ? currentKeyEvent->mKeyEvent : nullptr; keydownEvent.mNativeKeyEvent = keypressEvent.mNativeKeyEvent = keyEvent; - NS_WARNING_ASSERTION(keypressEvent.mNativeKeyEvent, - "Without native key event, NativeKeyBindings cannot compute aCommand"); + NS_WARNING_ASSERTION( + keypressEvent.mNativeKeyEvent, + "Without native key event, NativeKeyBindings cannot compute aCommand"); switch (aCommand) { case Command::InsertLineBreak: case Command::InsertParagraph: { @@ -2621,7 +2766,8 @@ bool TextInputHandler::HandleCommand(Command aCommand) { nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent); keypressEvent.mKeyCode = NS_VK_RETURN; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Enter; - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); if (aCommand == Command::InsertLineBreak) { // In default settings, Ctrl + Enter causes insertLineBreak command. // So, let's make Ctrl state active of the keypress event. @@ -2634,7 +2780,8 @@ bool TextInputHandler::HandleCommand(Command aCommand) { nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent); keypressEvent.mKeyCode = NS_VK_TAB; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Tab; - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); if (aCommand == Command::InsertBacktab) { keypressEvent.mModifiers |= MODIFIER_SHIFT; } @@ -2645,7 +2792,8 @@ bool TextInputHandler::HandleCommand(Command aCommand) { nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent); keypressEvent.mKeyCode = NS_VK_BACK; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Backspace; - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); if (aCommand == Command::DeleteToBeginningOfLine) { keypressEvent.mModifiers |= MODIFIER_META; } else if (aCommand == Command::DeleteWordBackward) { @@ -2658,7 +2806,8 @@ bool TextInputHandler::HandleCommand(Command aCommand) { nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent); keypressEvent.mKeyCode = NS_VK_DELETE; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Delete; - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); if (aCommand == Command::DeleteWordForward) { keypressEvent.mModifiers |= MODIFIER_ALT; } @@ -2673,15 +2822,19 @@ bool TextInputHandler::HandleCommand(Command aCommand) { nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent); keypressEvent.mKeyCode = NS_VK_RIGHT; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_ArrowRight; - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); - if (aCommand == Command::SelectCharNext || aCommand == Command::SelectWordNext || + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + if (aCommand == Command::SelectCharNext || + aCommand == Command::SelectWordNext || aCommand == Command::SelectEndLine) { keypressEvent.mModifiers |= MODIFIER_SHIFT; } - if (aCommand == Command::WordNext || aCommand == Command::SelectWordNext) { + if (aCommand == Command::WordNext || + aCommand == Command::SelectWordNext) { keypressEvent.mModifiers |= MODIFIER_ALT; } - if (aCommand == Command::EndLine || aCommand == Command::SelectEndLine) { + if (aCommand == Command::EndLine || + aCommand == Command::SelectEndLine) { keypressEvent.mModifiers |= MODIFIER_META; } break; @@ -2695,15 +2848,19 @@ bool TextInputHandler::HandleCommand(Command aCommand) { nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent); keypressEvent.mKeyCode = NS_VK_LEFT; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_ArrowLeft; - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); - if (aCommand == Command::SelectCharPrevious || aCommand == Command::SelectWordPrevious || + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + if (aCommand == Command::SelectCharPrevious || + aCommand == Command::SelectWordPrevious || aCommand == Command::SelectBeginLine) { keypressEvent.mModifiers |= MODIFIER_SHIFT; } - if (aCommand == Command::WordPrevious || aCommand == Command::SelectWordPrevious) { + if (aCommand == Command::WordPrevious || + aCommand == Command::SelectWordPrevious) { keypressEvent.mModifiers |= MODIFIER_ALT; } - if (aCommand == Command::BeginLine || aCommand == Command::SelectBeginLine) { + if (aCommand == Command::BeginLine || + aCommand == Command::SelectBeginLine) { keypressEvent.mModifiers |= MODIFIER_META; } break; @@ -2715,8 +2872,10 @@ bool TextInputHandler::HandleCommand(Command aCommand) { nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent); keypressEvent.mKeyCode = NS_VK_UP; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_ArrowUp; - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); - if (aCommand == Command::SelectLinePrevious || aCommand == Command::SelectTop) { + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + if (aCommand == Command::SelectLinePrevious || + aCommand == Command::SelectTop) { keypressEvent.mModifiers |= MODIFIER_SHIFT; } if (aCommand == Command::MoveTop || aCommand == Command::SelectTop) { @@ -2731,11 +2890,14 @@ bool TextInputHandler::HandleCommand(Command aCommand) { nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent); keypressEvent.mKeyCode = NS_VK_DOWN; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_ArrowDown; - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); - if (aCommand == Command::SelectLineNext || aCommand == Command::SelectBottom) { + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + if (aCommand == Command::SelectLineNext || + aCommand == Command::SelectBottom) { keypressEvent.mModifiers |= MODIFIER_SHIFT; } - if (aCommand == Command::MoveBottom || aCommand == Command::SelectBottom) { + if (aCommand == Command::MoveBottom || + aCommand == Command::SelectBottom) { keypressEvent.mModifiers |= MODIFIER_META; } break; @@ -2745,7 +2907,8 @@ bool TextInputHandler::HandleCommand(Command aCommand) { nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent); keypressEvent.mKeyCode = NS_VK_PAGE_UP; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_PageUp; - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); if (aCommand == Command::SelectPageUp) { keypressEvent.mModifiers |= MODIFIER_SHIFT; } @@ -2756,7 +2919,8 @@ bool TextInputHandler::HandleCommand(Command aCommand) { nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent); keypressEvent.mKeyCode = NS_VK_PAGE_DOWN; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_PageDown; - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); if (aCommand == Command::SelectPageDown) { keypressEvent.mModifiers |= MODIFIER_SHIFT; } @@ -2772,7 +2936,8 @@ bool TextInputHandler::HandleCommand(Command aCommand) { keypressEvent.mKeyCode = NS_VK_HOME; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Home; } - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); break; } case Command::CancelOperation: @@ -2780,7 +2945,8 @@ bool TextInputHandler::HandleCommand(Command aCommand) { nsCocoaUtils::InitInputEvent(keypressEvent, keyEvent); keypressEvent.mKeyCode = NS_VK_ESCAPE; keypressEvent.mKeyNameIndex = KEY_NAME_INDEX_Escape; - keypressEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + keypressEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); if (aCommand == Command::Complete) { keypressEvent.mModifiers |= MODIFIER_ALT; } @@ -2802,7 +2968,8 @@ bool TextInputHandler::HandleCommand(Command aCommand) { // "keydown" event. However, Chrome also dispatches such fake "keydown" // (and "keypress") event for making same behavior as Safari. nsEventStatus status = nsEventStatus_eIgnore; - if (mDispatcher->DispatchKeyboardEvent(eKeyDown, keydownEvent, status, nullptr)) { + if (mDispatcher->DispatchKeyboardEvent(eKeyDown, keydownEvent, status, + nullptr)) { bool keydownHandled = status == nsEventStatus_eConsumeNoDefault; if (currentKeyEvent) { currentKeyEvent->mKeyDownDispatched = true; @@ -2819,8 +2986,8 @@ bool TextInputHandler::HandleCommand(Command aCommand) { } } - bool keyPressDispatched = - mDispatcher->MaybeDispatchKeypressEvents(keypressEvent, status, currentKeyEvent); + bool keyPressDispatched = mDispatcher->MaybeDispatchKeypressEvents( + keypressEvent, status, currentKeyEvent); bool keyPressHandled = (status == nsEventStatus_eConsumeNoDefault); // NOTE: mWidget might have become null here. @@ -2839,8 +3006,10 @@ bool TextInputHandler::HandleCommand(Command aCommand) { // If keypress event isn't dispatched as expected, we should fallback to // using composition events. - if (aCommand == Command::InsertLineBreak || aCommand == Command::InsertParagraph) { - NSAttributedString* lineBreaker = [[NSAttributedString alloc] initWithString:@"\n"]; + if (aCommand == Command::InsertLineBreak || + aCommand == Command::InsertParagraph) { + NSAttributedString* lineBreaker = + [[NSAttributedString alloc] initWithString:@"\n"]; InsertTextAsCommittingComposition(lineBreaker, nullptr); if (currentKeyEvent) { currentKeyEvent->mCompositionDispatched = true; @@ -2865,11 +3034,14 @@ bool TextInputHandler::DoCommandBySelector(const char* aSelector) { "Destroyed()=%s, keydownDispatched=%s, keydownHandled=%s, " "keypressDispatched=%s, keypressHandled=%s, causedOtherKeyEvents=%s", this, aSelector ? aSelector : "", TrueOrFalse(Destroyed()), - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownDispatched) : "N/A", + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownDispatched) + : "N/A", currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownHandled) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched) : "N/A", + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched) + : "N/A", currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressHandled) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents) : "N/A")); + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents) + : "N/A")); // If the command isn't caused by key operation, the command should // be handled in the super class of the caller. @@ -2883,10 +3055,11 @@ bool TextInputHandler::DoCommandBySelector(const char* aSelector) { // TextInputHandler::HandleKeyDownEvent(). RefPtr kungFuDeathGrip(this); if (!IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(false)) { - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandler::SetMarkedText, eKeyDown caused focus move or " - "something and canceling the composition", - this)); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandler::SetMarkedText, eKeyDown caused focus move or " + "something and canceling the composition", + this)); return true; } @@ -2899,10 +3072,12 @@ bool TextInputHandler::DoCommandBySelector(const char* aSelector) { if (currentKeyEvent->CanDispatchKeyPressEvent()) { nsresult rv = mDispatcher->BeginNativeInputTransaction(); if (NS_WARN_IF(NS_FAILED(rv))) { - MOZ_LOG_KEY_OR_IME(LogLevel::Error, ("%p TextInputHandler::DoCommandBySelector, " - "FAILED, due to BeginNativeInputTransaction() failure " - "at dispatching keypress", - this)); + MOZ_LOG_KEY_OR_IME( + LogLevel::Error, + ("%p TextInputHandler::DoCommandBySelector, " + "FAILED, due to BeginNativeInputTransaction() failure " + "at dispatching keypress", + this)); return Destroyed(); } @@ -2911,13 +3086,16 @@ bool TextInputHandler::DoCommandBySelector(const char* aSelector) { nsEventStatus status = nsEventStatus_eIgnore; currentKeyEvent->mKeyPressDispatched = - mDispatcher->MaybeDispatchKeypressEvents(keypressEvent, status, currentKeyEvent); - currentKeyEvent->mKeyPressHandled = (status == nsEventStatus_eConsumeNoDefault); + mDispatcher->MaybeDispatchKeypressEvents(keypressEvent, status, + currentKeyEvent); + currentKeyEvent->mKeyPressHandled = + (status == nsEventStatus_eConsumeNoDefault); MOZ_LOG_KEY_OR_IME( LogLevel::Info, ("%p TextInputHandler::DoCommandBySelector, keypress event " "dispatched, Destroyed()=%s, keypressHandled=%s", - this, TrueOrFalse(Destroyed()), TrueOrFalse(currentKeyEvent->mKeyPressHandled))); + this, TrueOrFalse(Destroyed()), + TrueOrFalse(currentKeyEvent->mKeyPressHandled))); // This command is now dispatched with keypress event. // So, this shouldn't be handled by nobody anymore. return true; @@ -2972,19 +3150,19 @@ void IMEInputHandler::InitStaticMembers() { // XXX Don't we need to remove the observer at shut down? // Mac Dev Center's document doesn't say how to remove the observer if // the second parameter is NULL. - ::CFNotificationCenterAddObserver(center, NULL, OnCurrentTextInputSourceChange, - kTISNotifySelectedKeyboardInputSourceChanged, NULL, - CFNotificationSuspensionBehaviorDeliverImmediately); + ::CFNotificationCenterAddObserver( + center, NULL, OnCurrentTextInputSourceChange, + kTISNotifySelectedKeyboardInputSourceChanged, NULL, + CFNotificationSuspensionBehaviorDeliverImmediately); // Initiailize with the current keyboard layout - OnCurrentTextInputSourceChange(NULL, NULL, kTISNotifySelectedKeyboardInputSourceChanged, NULL, - NULL); + OnCurrentTextInputSourceChange( + NULL, NULL, kTISNotifySelectedKeyboardInputSourceChanged, NULL, NULL); } // static -void IMEInputHandler::OnCurrentTextInputSourceChange(CFNotificationCenterRef aCenter, - void* aObserver, CFStringRef aName, - const void* aObject, - CFDictionaryRef aUserInfo) { +void IMEInputHandler::OnCurrentTextInputSourceChange( + CFNotificationCenterRef aCenter, void* aObserver, CFStringRef aName, + const void* aObject, CFDictionaryRef aUserInfo) { // Cache the latest IME opened mode to sLatestIMEOpenedModeInputSourceID. TISInputSourceWrapper tis; tis.InitByCurrentInputSource(); @@ -3016,22 +3194,25 @@ void IMEInputHandler::OnCurrentTextInputSourceChange(CFNotificationCenterRef aCe // U+2026 is "..." key.Append(char16_t(0x2026)); } - Telemetry::ScalarSet(Telemetry::ScalarID::WIDGET_IME_NAME_ON_MAC, key, true); + Telemetry::ScalarSet(Telemetry::ScalarID::WIDGET_IME_NAME_ON_MAC, key, + true); } if (MOZ_LOG_TEST(gIMELog, LogLevel::Info)) { static CFStringRef sLastTIS = nullptr; CFStringRef newTIS; tis.GetInputSourceID(newTIS); - if (!sLastTIS || ::CFStringCompare(sLastTIS, newTIS, 0) != kCFCompareEqualTo) { + if (!sLastTIS || + ::CFStringCompare(sLastTIS, newTIS, 0) != kCFCompareEqualTo) { TISInputSourceWrapper tis1, tis2, tis3, tis4, tis5; tis1.InitByCurrentKeyboardLayout(); tis2.InitByCurrentASCIICapableInputSource(); tis3.InitByCurrentASCIICapableKeyboardLayout(); tis4.InitByCurrentInputMethodKeyboardLayoutOverride(); tis5.InitByTISInputSourceRef(tis.GetKeyboardLayoutInputSource()); - CFStringRef is0 = nullptr, is1 = nullptr, is2 = nullptr, is3 = nullptr, is4 = nullptr, - is5 = nullptr, type0 = nullptr, lang0 = nullptr, bundleID0 = nullptr; + CFStringRef is0 = nullptr, is1 = nullptr, is2 = nullptr, is3 = nullptr, + is4 = nullptr, is5 = nullptr, type0 = nullptr, + lang0 = nullptr, bundleID0 = nullptr; tis.GetInputSourceID(is0); tis1.GetInputSourceID(is1); tis2.GetInputSourceID(is2); @@ -3042,23 +3223,25 @@ void IMEInputHandler::OnCurrentTextInputSourceChange(CFNotificationCenterRef aCe tis.GetPrimaryLanguage(lang0); tis.GetBundleID(bundleID0); - MOZ_LOG(gIMELog, LogLevel::Info, - ("IMEInputHandler::OnCurrentTextInputSourceChange,\n" - " Current Input Source is changed to:\n" - " currentInputContext=%p\n" - " %s\n" - " type=%s %s\n" - " overridden keyboard layout=%s\n" - " used keyboard layout for translation=%s\n" - " primary language=%s\n" - " bundle ID=%s\n" - " current ASCII capable Input Source=%s\n" - " current Keyboard Layout=%s\n" - " current ASCII capable Keyboard Layout=%s", - [NSTextInputContext currentInputContext], GetCharacters(is0), GetCharacters(type0), - tis.IsASCIICapable() ? "- ASCII capable " : "", GetCharacters(is4), - GetCharacters(is5), GetCharacters(lang0), GetCharacters(bundleID0), - GetCharacters(is2), GetCharacters(is1), GetCharacters(is3))); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("IMEInputHandler::OnCurrentTextInputSourceChange,\n" + " Current Input Source is changed to:\n" + " currentInputContext=%p\n" + " %s\n" + " type=%s %s\n" + " overridden keyboard layout=%s\n" + " used keyboard layout for translation=%s\n" + " primary language=%s\n" + " bundle ID=%s\n" + " current ASCII capable Input Source=%s\n" + " current Keyboard Layout=%s\n" + " current ASCII capable Keyboard Layout=%s", + [NSTextInputContext currentInputContext], GetCharacters(is0), + GetCharacters(type0), tis.IsASCIICapable() ? "- ASCII capable " : "", + GetCharacters(is4), GetCharacters(is5), GetCharacters(lang0), + GetCharacters(bundleID0), GetCharacters(is2), GetCharacters(is1), + GetCharacters(is3))); } sLastTIS = newTIS; } @@ -3084,7 +3267,8 @@ void IMEInputHandler::FlushPendingMethods(nsITimer* aTimer, void* aClosure) { CFArrayRef IMEInputHandler::CreateAllIMEModeList() { const void* keys[] = {kTISPropertyInputSourceType}; const void* values[] = {kTISTypeKeyboardInputMode}; - CFDictionaryRef filter = ::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL); + CFDictionaryRef filter = + ::CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL); NS_ASSERTION(filter, "failed to create the filter"); CFArrayRef list = ::TISCreateInputSourceList(filter, true); ::CFRelease(filter); @@ -3099,19 +3283,21 @@ void IMEInputHandler::DebugPrintAllIMEModes() { CFIndex idx = ::CFArrayGetCount(list); TISInputSourceWrapper tis; for (CFIndex i = 0; i < idx; ++i) { - TISInputSourceRef inputSource = - static_cast(const_cast(::CFArrayGetValueAtIndex(list, i))); + TISInputSourceRef inputSource = static_cast( + const_cast(::CFArrayGetValueAtIndex(list, i))); tis.InitByTISInputSourceRef(inputSource); nsAutoString name, isid, bundleID; tis.GetLocalizedName(name); tis.GetInputSourceID(isid); tis.GetBundleID(bundleID); - MOZ_LOG(gIMELog, LogLevel::Info, - (" %s\t<%s>%s%s\n" - " bundled in <%s>\n", - NS_ConvertUTF16toUTF8(name).get(), NS_ConvertUTF16toUTF8(isid).get(), - tis.IsASCIICapable() ? "" : "\t(Isn't ASCII capable)", - tis.IsEnabled() ? "" : "\t(Isn't Enabled)", NS_ConvertUTF16toUTF8(bundleID).get())); + MOZ_LOG( + gIMELog, LogLevel::Info, + (" %s\t<%s>%s%s\n" + " bundled in <%s>\n", + NS_ConvertUTF16toUTF8(name).get(), NS_ConvertUTF16toUTF8(isid).get(), + tis.IsASCIICapable() ? "" : "\t(Isn't ASCII capable)", + tis.IsEnabled() ? "" : "\t(Isn't Enabled)", + NS_ConvertUTF16toUTF8(bundleID).get())); } ::CFRelease(list); } @@ -3153,10 +3339,12 @@ nsresult IMEInputHandler::NotifyIME(TextEventDispatcher* aTextEventDispatcher, case NOTIFY_IME_OF_FOCUS: if (IsFocused()) { nsIWidget* widget = aTextEventDispatcher->GetWidget(); - MOZ_LOG( - gIMELog, LogLevel::Debug, - ("%p IMEInputHandler::NotifyIME(), IsFocused()=true, widget=%p, IsPasswordEditor()=%s", - this, widget, TrueOrFalse(widget && widget->GetInputContext().IsPasswordEditor()))); + MOZ_LOG(gIMELog, LogLevel::Debug, + ("%p IMEInputHandler::NotifyIME(), IsFocused()=true, " + "widget=%p, IsPasswordEditor()=%s", + this, widget, + TrueOrFalse(widget && + widget->GetInputContext().IsPasswordEditor()))); if (widget && widget->GetInputContext().IsPasswordEditor()) { EnableSecureEventInput(); } else { @@ -3165,13 +3353,15 @@ nsresult IMEInputHandler::NotifyIME(TextEventDispatcher* aTextEventDispatcher, } else if (MOZ_LOG_TEST(gIMELog, LogLevel::Debug)) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN NSWindow* window = mView ? [mView window] : nil; - MOZ_LOG( - gIMELog, LogLevel::Debug, - ("%p IMEInputHandler::NotifyIME(), IsFocused()=false, Destroyed()=%s, mView=%p, " - "[mView window]=%p, firstResponder=%p, isKeyWindow=%s, isActive=%s", - this, TrueOrFalse(Destroyed()), mView, window, window ? [window firstResponder] : nil, - TrueOrFalse(window && [window isKeyWindow]), - TrueOrFalse([[NSApplication sharedApplication] isActive]))); + MOZ_LOG(gIMELog, LogLevel::Debug, + ("%p IMEInputHandler::NotifyIME(), IsFocused()=false, " + "Destroyed()=%s, mView=%p, " + "[mView window]=%p, firstResponder=%p, isKeyWindow=%s, " + "isActive=%s", + this, TrueOrFalse(Destroyed()), mView, window, + window ? [window firstResponder] : nil, + TrueOrFalse(window && [window isKeyWindow]), + TrueOrFalse([[NSApplication sharedApplication] isActive]))); NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE) } OnFocusChangeInGecko(true); @@ -3204,9 +3394,10 @@ IMEInputHandler::OnRemovedFrom(TextEventDispatcher* aTextEventDispatcher) { } NS_IMETHODIMP_(void) -IMEInputHandler::WillDispatchKeyboardEvent(TextEventDispatcher* aTextEventDispatcher, - WidgetKeyboardEvent& aKeyboardEvent, - uint32_t aIndexOfKeypress, void* aData) { +IMEInputHandler::WillDispatchKeyboardEvent( + TextEventDispatcher* aTextEventDispatcher, + WidgetKeyboardEvent& aKeyboardEvent, uint32_t aIndexOfKeypress, + void* aData) { // If the keyboard event is not caused by a native key event, we can do // nothing here. if (!aData) { @@ -3230,7 +3421,8 @@ IMEInputHandler::WillDispatchKeyboardEvent(TextEventDispatcher* aTextEventDispat if (KeyboardLayoutOverrideRef().mOverrideEnabled) { TISInputSourceWrapper tis; tis.InitByLayoutID(KeyboardLayoutOverrideRef().mKeyboardLayout, true); - tis.WillDispatchKeyboardEvent(nativeEvent, insertString, aIndexOfKeypress, aKeyboardEvent); + tis.WillDispatchKeyboardEvent(nativeEvent, insertString, aIndexOfKeypress, + aKeyboardEvent); } else { TISInputSourceWrapper::CurrentInputSource().WillDispatchKeyboardEvent( nativeEvent, insertString, aIndexOfKeypress, aKeyboardEvent); @@ -3242,9 +3434,10 @@ IMEInputHandler::WillDispatchKeyboardEvent(TextEventDispatcher* aTextEventDispat // Note that this hack should be used only when an editor has focus because // this is a hack for TextEditor and modifier key information may be // important for current web app. - if (IsEditableContent() && insertString && aKeyboardEvent.mMessage == eKeyPress && - aKeyboardEvent.mCharCode) { - aKeyboardEvent.mModifiers &= ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); + if (IsEditableContent() && insertString && + aKeyboardEvent.mMessage == eKeyPress && aKeyboardEvent.mCharCode) { + aKeyboardEvent.mModifiers &= + ~(MODIFIER_CONTROL | MODIFIER_ALT | MODIFIER_META); } } @@ -3316,25 +3509,28 @@ void IMEInputHandler::SyncASCIICapableOnly() { if (mIsASCIICapableOnly) { CFArrayRef ASCIICapableTISList = ::TISCreateASCIICapableInputSourceList(); - ::TSMSetDocumentProperty(doc, kTSMDocumentEnabledInputSourcesPropertyTag, sizeof(CFArrayRef), - &ASCIICapableTISList); + ::TSMSetDocumentProperty(doc, kTSMDocumentEnabledInputSourcesPropertyTag, + sizeof(CFArrayRef), &ASCIICapableTISList); ::CFRelease(ASCIICapableTISList); } else { - ::TSMRemoveDocumentProperty(doc, kTSMDocumentEnabledInputSourcesPropertyTag); + ::TSMRemoveDocumentProperty(doc, + kTSMDocumentEnabledInputSourcesPropertyTag); } NS_OBJC_END_TRY_IGNORE_BLOCK; } void IMEInputHandler::ResetTimer() { - NS_ASSERTION(mPendingMethods != 0, "There are not pending methods, why this is called?"); + NS_ASSERTION(mPendingMethods != 0, + "There are not pending methods, why this is called?"); if (mTimer) { mTimer->Cancel(); } else { mTimer = NS_NewTimer(); NS_ENSURE_TRUE(mTimer, ); } - mTimer->InitWithNamedFuncCallback(FlushPendingMethods, this, 0, nsITimer::TYPE_ONE_SHOT, + mTimer->InitWithNamedFuncCallback(FlushPendingMethods, this, 0, + nsITimer::TYPE_ONE_SHOT, "IMEInputHandler::FlushPendingMethods"); } @@ -3377,7 +3573,8 @@ TextRangeType IMEInputHandler::ConvertToTextRangeType(uint32_t aUnderlineStyle, MOZ_LOG(gIMELog, LogLevel::Info, ("%p IMEInputHandler::ConvertToTextRangeType, " "aUnderlineStyle=%u, aSelectedRange.length=%lu,", - this, aUnderlineStyle, static_cast(aSelectedRange.length))); + this, aUnderlineStyle, + static_cast(aSelectedRange.length))); // We assume that aUnderlineStyle is NSUnderlineStyleSingle or // NSUnderlineStyleThick. NSUnderlineStyleThick should indicate a selected @@ -3419,14 +3616,15 @@ uint32_t IMEInputHandler::GetRangeCount(NSAttributedString* aAttrString) { atIndex:limitRange.location longestEffectiveRange:&effectiveRange inRange:limitRange]; - limitRange = NSMakeRange(NSMaxRange(effectiveRange), - NSMaxRange(limitRange) - NSMaxRange(effectiveRange)); + limitRange = + NSMakeRange(NSMaxRange(effectiveRange), + NSMaxRange(limitRange) - NSMaxRange(effectiveRange)); count++; } MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::GetRangeCount, aAttrString=\"%s\", count=%u", this, - GetCharacters([aAttrString string]), count)); + ("%p IMEInputHandler::GetRangeCount, aAttrString=\"%s\", count=%u", + this, GetCharacters([aAttrString string]), count)); return count; @@ -3437,7 +3635,8 @@ already_AddRefed IMEInputHandler::CreateTextRangeArray( NSAttributedString* aAttrString, NSRange& aSelectedRange) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - RefPtr textRangeArray = new mozilla::TextRangeArray(); + RefPtr textRangeArray = + new mozilla::TextRangeArray(); // Note that we shouldn't append ranges when composition string // is empty because it may cause TextComposition confused. @@ -3461,16 +3660,19 @@ already_AddRefed IMEInputHandler::CreateTextRangeArray( TextRange range; range.mStartOffset = effectiveRange.location; range.mEndOffset = NSMaxRange(effectiveRange); - range.mRangeType = ConvertToTextRangeType([attributeValue intValue], aSelectedRange); + range.mRangeType = + ConvertToTextRangeType([attributeValue intValue], aSelectedRange); textRangeArray->AppendElement(range); - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::CreateTextRangeArray, " - "range={ mStartOffset=%u, mEndOffset=%u, mRangeType=%s }", - this, range.mStartOffset, range.mEndOffset, ToChar(range.mRangeType))); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::CreateTextRangeArray, " + "range={ mStartOffset=%u, mEndOffset=%u, mRangeType=%s }", + this, range.mStartOffset, range.mEndOffset, ToChar(range.mRangeType))); - limitRange = NSMakeRange(NSMaxRange(effectiveRange), - NSMaxRange(limitRange) - NSMaxRange(effectiveRange)); + limitRange = + NSMakeRange(NSMaxRange(effectiveRange), + NSMaxRange(limitRange) - NSMaxRange(effectiveRange)); } // Get current caret position. @@ -3480,10 +3682,11 @@ already_AddRefed IMEInputHandler::CreateTextRangeArray( range.mRangeType = TextRangeType::eCaret; textRangeArray->AppendElement(range); - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::CreateTextRangeArray, " - "range={ mStartOffset=%u, mEndOffset=%u, mRangeType=%s }", - this, range.mStartOffset, range.mEndOffset, ToChar(range.mRangeType))); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::CreateTextRangeArray, " + "range={ mStartOffset=%u, mEndOffset=%u, mRangeType=%s }", + this, range.mStartOffset, range.mEndOffset, ToChar(range.mRangeType))); return textRangeArray.forget(); @@ -3491,13 +3694,15 @@ already_AddRefed IMEInputHandler::CreateTextRangeArray( } bool IMEInputHandler::DispatchCompositionStartEvent() { - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::DispatchCompositionStartEvent, " - "mSelectedRange={ location=%lu, length=%lu }, Destroyed()=%s, " - "mView=%p, mWidget=%p, inputContext=%p, mIsIMEComposing=%s", - this, static_cast(SelectedRange().location), - static_cast(mSelectedRange.length), TrueOrFalse(Destroyed()), mView, - mWidget, mView ? [mView inputContext] : nullptr, TrueOrFalse(mIsIMEComposing))); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::DispatchCompositionStartEvent, " + "mSelectedRange={ location=%lu, length=%lu }, Destroyed()=%s, " + "mView=%p, mWidget=%p, inputContext=%p, mIsIMEComposing=%s", + this, static_cast(SelectedRange().location), + static_cast(mSelectedRange.length), + TrueOrFalse(Destroyed()), mView, mWidget, + mView ? [mView inputContext] : nullptr, TrueOrFalse(mIsIMEComposing))); RefPtr kungFuDeathGrip(this); @@ -3513,9 +3718,9 @@ bool IMEInputHandler::DispatchCompositionStartEvent() { NS_ASSERTION(!mIsIMEComposing, "There is a composition already"); mIsIMEComposing = true; KeyEventState* currentKeyEvent = GetCurrentKeyEvent(); - mIsDeadKeyComposing = - currentKeyEvent && currentKeyEvent->mKeyEvent && - TISInputSourceWrapper::CurrentInputSource().IsDeadKey(currentKeyEvent->mKeyEvent); + mIsDeadKeyComposing = currentKeyEvent && currentKeyEvent->mKeyEvent && + TISInputSourceWrapper::CurrentInputSource().IsDeadKey( + currentKeyEvent->mKeyEvent); nsEventStatus status; rv = mDispatcher->StartComposition(status); @@ -3546,20 +3751,23 @@ bool IMEInputHandler::DispatchCompositionStartEvent() { return true; } -bool IMEInputHandler::DispatchCompositionChangeEvent(const nsString& aText, - NSAttributedString* aAttrString, - NSRange& aSelectedRange) { +bool IMEInputHandler::DispatchCompositionChangeEvent( + const nsString& aText, NSAttributedString* aAttrString, + NSRange& aSelectedRange) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::DispatchCompositionChangeEvent, " - "aText=\"%s\", aAttrString=\"%s\", " - "aSelectedRange={ location=%lu, length=%lu }, Destroyed()=%s, mView=%p, " - "mWidget=%p, inputContext=%p, mIsIMEComposing=%s", - this, NS_ConvertUTF16toUTF8(aText).get(), GetCharacters([aAttrString string]), - static_cast(aSelectedRange.location), - static_cast(aSelectedRange.length), TrueOrFalse(Destroyed()), mView, - mWidget, mView ? [mView inputContext] : nullptr, TrueOrFalse(mIsIMEComposing))); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::DispatchCompositionChangeEvent, " + "aText=\"%s\", aAttrString=\"%s\", " + "aSelectedRange={ location=%lu, length=%lu }, Destroyed()=%s, mView=%p, " + "mWidget=%p, inputContext=%p, mIsIMEComposing=%s", + this, NS_ConvertUTF16toUTF8(aText).get(), + GetCharacters([aAttrString string]), + static_cast(aSelectedRange.location), + static_cast(aSelectedRange.length), + TrueOrFalse(Destroyed()), mView, mWidget, + mView ? [mView inputContext] : nullptr, TrueOrFalse(mIsIMEComposing))); NS_ENSURE_TRUE(!Destroyed(), false); @@ -3576,7 +3784,8 @@ bool IMEInputHandler::DispatchCompositionChangeEvent(const nsString& aText, return false; } - RefPtr rangeArray = CreateTextRangeArray(aAttrString, aSelectedRange); + RefPtr rangeArray = + CreateTextRangeArray(aAttrString, aSelectedRange); rv = mDispatcher->SetPendingComposition(aText, rangeArray); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -3619,16 +3828,19 @@ bool IMEInputHandler::DispatchCompositionChangeEvent(const nsString& aText, NS_OBJC_END_TRY_BLOCK_RETURN(false); } -bool IMEInputHandler::DispatchCompositionCommitEvent(const nsAString* aCommitString) { +bool IMEInputHandler::DispatchCompositionCommitEvent( + const nsAString* aCommitString) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::DispatchCompositionCommitEvent, " - "aCommitString=0x%p (\"%s\"), Destroyed()=%s, mView=%p, mWidget=%p, " - "inputContext=%p, mIsIMEComposing=%s", - this, aCommitString, aCommitString ? NS_ConvertUTF16toUTF8(*aCommitString).get() : "", - TrueOrFalse(Destroyed()), mView, mWidget, mView ? [mView inputContext] : nullptr, - TrueOrFalse(mIsIMEComposing))); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::DispatchCompositionCommitEvent, " + "aCommitString=0x%p (\"%s\"), Destroyed()=%s, mView=%p, mWidget=%p, " + "inputContext=%p, mIsIMEComposing=%s", + this, aCommitString, + aCommitString ? NS_ConvertUTF16toUTF8(*aCommitString).get() : "", + TrueOrFalse(Destroyed()), mView, mWidget, + mView ? [mView inputContext] : nullptr, TrueOrFalse(mIsIMEComposing))); NS_ASSERTION(mIsIMEComposing, "We're not in composition"); @@ -3704,13 +3916,15 @@ bool IMEInputHandler::MaybeDispatchCurrentKeydownEvent(bool aIsProcessedByIME) { return true; } - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::MaybeDispatchKeydownEvent, aIsProcessedByIME=%s " - "currentKeyEvent={ mKeyEvent(%p)={ type=%s, keyCode=%s (0x%X) } }, " - "aIsProcessedBy=%s, IsDeadKeyComposing()=%s", - this, TrueOrFalse(aIsProcessedByIME), nativeEvent, GetNativeKeyEventType(nativeEvent), - GetKeyNameForNativeKeyCode([nativeEvent keyCode]), [nativeEvent keyCode], - TrueOrFalse(IsIMEComposing()), TrueOrFalse(IsDeadKeyComposing()))); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::MaybeDispatchKeydownEvent, aIsProcessedByIME=%s " + "currentKeyEvent={ mKeyEvent(%p)={ type=%s, keyCode=%s (0x%X) } }, " + "aIsProcessedBy=%s, IsDeadKeyComposing()=%s", + this, TrueOrFalse(aIsProcessedByIME), nativeEvent, + GetNativeKeyEventType(nativeEvent), + GetKeyNameForNativeKeyCode([nativeEvent keyCode]), [nativeEvent keyCode], + TrueOrFalse(IsIMEComposing()), TrueOrFalse(IsDeadKeyComposing()))); RefPtr kungFuDeathGrip(this); RefPtr dispatcher(mDispatcher); @@ -3733,11 +3947,14 @@ bool IMEInputHandler::MaybeDispatchCurrentKeydownEvent(bool aIsProcessedByIME) { WidgetKeyboardEvent keydownEvent(true, eKeyDown, widget); // Don't mark the eKeyDown event as "processed by IME" if the composition // is started with dead key. - currentKeyEvent->InitKeyEvent(this, keydownEvent, aIsProcessedByIME && !IsDeadKeyComposing()); + currentKeyEvent->InitKeyEvent(this, keydownEvent, + aIsProcessedByIME && !IsDeadKeyComposing()); nsEventStatus status = nsEventStatus_eIgnore; - dispatcher->DispatchKeyboardEvent(eKeyDown, keydownEvent, status, currentKeyEvent); - currentKeyEvent->mKeyDownHandled = (status == nsEventStatus_eConsumeNoDefault); + dispatcher->DispatchKeyboardEvent(eKeyDown, keydownEvent, status, + currentKeyEvent); + currentKeyEvent->mKeyDownHandled = + (status == nsEventStatus_eConsumeNoDefault); if (Destroyed()) { MOZ_LOG(gIMELog, LogLevel::Info, @@ -3764,21 +3981,24 @@ bool IMEInputHandler::MaybeDispatchCurrentKeydownEvent(bool aIsProcessedByIME) { NS_OBJC_END_TRY_BLOCK_RETURN(false); } -void IMEInputHandler::InsertTextAsCommittingComposition(NSAttributedString* aAttrString, - NSRange* aReplacementRange) { +void IMEInputHandler::InsertTextAsCommittingComposition( + NSAttributedString* aAttrString, NSRange* aReplacementRange) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::InsertTextAsCommittingComposition, " - "aAttrString=\"%s\", aReplacementRange=%p { location=%lu, length=%lu }, " - "Destroyed()=%s, IsIMEComposing()=%s, " - "mMarkedRange={ location=%lu, length=%lu }", - this, GetCharacters([aAttrString string]), aReplacementRange, - static_cast(aReplacementRange ? aReplacementRange->location : 0), - static_cast(aReplacementRange ? aReplacementRange->length : 0), - TrueOrFalse(Destroyed()), TrueOrFalse(IsIMEComposing()), - static_cast(mMarkedRange.location), - static_cast(mMarkedRange.length))); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::InsertTextAsCommittingComposition, " + "aAttrString=\"%s\", aReplacementRange=%p { location=%lu, length=%lu }, " + "Destroyed()=%s, IsIMEComposing()=%s, " + "mMarkedRange={ location=%lu, length=%lu }", + this, GetCharacters([aAttrString string]), aReplacementRange, + static_cast( + aReplacementRange ? aReplacementRange->location : 0), + static_cast(aReplacementRange ? aReplacementRange->length + : 0), + TrueOrFalse(Destroyed()), TrueOrFalse(IsIMEComposing()), + static_cast(mMarkedRange.location), + static_cast(mMarkedRange.length))); if (IgnoreIMECommit()) { MOZ_CRASH("IMEInputHandler::InsertTextAsCommittingComposition() must not" @@ -3799,22 +4019,25 @@ void IMEInputHandler::InsertTextAsCommittingComposition(NSAttributedString* aAtt // HandleKeyDownEvent() before do that. RefPtr kungFuDeathGrip(this); if (!IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(false)) { - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::InsertTextAsCommittingComposition, eKeyDown " - "caused focus move or something and canceling the composition", - this)); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::InsertTextAsCommittingComposition, eKeyDown " + "caused focus move or something and canceling the composition", + this)); return; } // First, commit current composition with the latest composition string if the // replacement range is different from marked range. - if (IsIMEComposing() && aReplacementRange && aReplacementRange->location != NSNotFound && + if (IsIMEComposing() && aReplacementRange && + aReplacementRange->location != NSNotFound && !NSEqualRanges(MarkedRange(), *aReplacementRange)) { if (!DispatchCompositionCommitEvent()) { - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::InsertTextAsCommittingComposition, " - "destroyed by commiting composition for setting replacement range", - this)); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::InsertTextAsCommittingComposition, " + "destroyed by commiting composition for setting replacement range", + this)); return; } } @@ -3837,7 +4060,8 @@ void IMEInputHandler::InsertTextAsCommittingComposition(NSAttributedString* aAtt // inserting text without key press nor IME composition because the // other browsers do so. This will cause only a cancelable `beforeinput` // event whose `inputType` is `insertText`. - WidgetContentCommandEvent insertTextEvent(true, eContentCommandInsertText, mWidget); + WidgetContentCommandEvent insertTextEvent(true, eContentCommandInsertText, + mWidget); insertTextEvent.mString = Some(str); DispatchEvent(insertTextEvent); return; @@ -3869,35 +4093,43 @@ void IMEInputHandler::InsertTextAsCommittingComposition(NSAttributedString* aAtt NS_OBJC_END_TRY_IGNORE_BLOCK; } -void IMEInputHandler::SetMarkedText(NSAttributedString* aAttrString, NSRange& aSelectedRange, +void IMEInputHandler::SetMarkedText(NSAttributedString* aAttrString, + NSRange& aSelectedRange, NSRange* aReplacementRange) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; KeyEventState* currentKeyEvent = GetCurrentKeyEvent(); - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::SetMarkedText, " - "aAttrString=\"%s\", aSelectedRange={ location=%lu, length=%lu }, " - "aReplacementRange=%p { location=%lu, length=%lu }, " - "Destroyed()=%s, IsIMEComposing()=%s, " - "mMarkedRange={ location=%lu, length=%lu }, keyevent=%p, " - "keydownDispatched=%s, keydownHandled=%s, " - "keypressDispatched=%s, causedOtherKeyEvents=%s, " - "compositionDispatched=%s", - this, GetCharacters([aAttrString string]), - static_cast(aSelectedRange.location), - static_cast(aSelectedRange.length), aReplacementRange, - static_cast(aReplacementRange ? aReplacementRange->location : 0), - static_cast(aReplacementRange ? aReplacementRange->length : 0), - TrueOrFalse(Destroyed()), TrueOrFalse(IsIMEComposing()), - static_cast(mMarkedRange.location), - static_cast(mMarkedRange.length), - currentKeyEvent ? currentKeyEvent->mKeyEvent : nullptr, - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownDispatched) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownHandled) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents) : "N/A", - currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCompositionDispatched) : "N/A")); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::SetMarkedText, " + "aAttrString=\"%s\", aSelectedRange={ location=%lu, length=%lu }, " + "aReplacementRange=%p { location=%lu, length=%lu }, " + "Destroyed()=%s, IsIMEComposing()=%s, " + "mMarkedRange={ location=%lu, length=%lu }, keyevent=%p, " + "keydownDispatched=%s, keydownHandled=%s, " + "keypressDispatched=%s, causedOtherKeyEvents=%s, " + "compositionDispatched=%s", + this, GetCharacters([aAttrString string]), + static_cast(aSelectedRange.location), + static_cast(aSelectedRange.length), aReplacementRange, + static_cast( + aReplacementRange ? aReplacementRange->location : 0), + static_cast(aReplacementRange ? aReplacementRange->length + : 0), + TrueOrFalse(Destroyed()), TrueOrFalse(IsIMEComposing()), + static_cast(mMarkedRange.location), + static_cast(mMarkedRange.length), + currentKeyEvent ? currentKeyEvent->mKeyEvent : nullptr, + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownDispatched) + : "N/A", + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyDownHandled) : "N/A", + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mKeyPressDispatched) + : "N/A", + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCausedOtherKeyEvents) + : "N/A", + currentKeyEvent ? TrueOrFalse(currentKeyEvent->mCompositionDispatched) + : "N/A")); RefPtr kungFuDeathGrip(this); @@ -3914,10 +4146,11 @@ void IMEInputHandler::SetMarkedText(NSAttributedString* aAttrString, NSRange& aS // not in composition, the key event starts new composition. So, we // need to mark the eKeyDown event as "processed by IME". if (!IsIMEComposing() && !MaybeDispatchCurrentKeydownEvent(true)) { - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::SetMarkedText, eKeyDown caused focus move or " - "something and canceling the composition", - this)); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::SetMarkedText, eKeyDown caused focus move or " + "something and canceling the composition", + this)); return; } } @@ -3928,15 +4161,17 @@ void IMEInputHandler::SetMarkedText(NSAttributedString* aAttrString, NSRange& aS // First, commit current composition with the latest composition string if the // replacement range is different from marked range. - if (IsIMEComposing() && aReplacementRange && aReplacementRange->location != NSNotFound && + if (IsIMEComposing() && aReplacementRange && + aReplacementRange->location != NSNotFound && !NSEqualRanges(MarkedRange(), *aReplacementRange)) { AutoRestore ignoreIMECommit(mIgnoreIMECommit); mIgnoreIMECommit = false; if (!DispatchCompositionCommitEvent()) { - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::SetMarkedText, " - "destroyed by commiting composition for setting replacement range", - this)); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::SetMarkedText, " + "destroyed by commiting composition for setting replacement range", + this)); return; } } @@ -3992,15 +4227,17 @@ void IMEInputHandler::SetMarkedText(NSAttributedString* aAttrString, NSRange& aS NS_OBJC_END_TRY_IGNORE_BLOCK; } -NSAttributedString* IMEInputHandler::GetAttributedSubstringFromRange(NSRange& aRange, - NSRange* aActualRange) { +NSAttributedString* IMEInputHandler::GetAttributedSubstringFromRange( + NSRange& aRange, NSRange* aActualRange) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::GetAttributedSubstringFromRange, " - "aRange={ location=%lu, length=%lu }, aActualRange=%p, Destroyed()=%s", - this, static_cast(aRange.location), - static_cast(aRange.length), aActualRange, TrueOrFalse(Destroyed()))); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::GetAttributedSubstringFromRange, " + "aRange={ location=%lu, length=%lu }, aActualRange=%p, Destroyed()=%s", + this, static_cast(aRange.location), + static_cast(aRange.length), aActualRange, + TrueOrFalse(Destroyed()))); if (aActualRange) { *aActualRange = NSMakeRange(NSNotFound, 0); @@ -4020,13 +4257,18 @@ NSAttributedString* IMEInputHandler::GetAttributedSubstringFromRange(NSRange& aR // that some attributes of marked text are supported, but they return // just marked string without any style. So, let's keep current behavior // at least for now. - NSUInteger compositionLength = mIMECompositionString ? [mIMECompositionString length] : 0; - if (mIMECompositionStart != UINT32_MAX && aRange.location >= mIMECompositionStart && - aRange.location + aRange.length <= mIMECompositionStart + compositionLength) { - NSRange range = NSMakeRange(aRange.location - mIMECompositionStart, aRange.length); + NSUInteger compositionLength = + mIMECompositionString ? [mIMECompositionString length] : 0; + if (mIMECompositionStart != UINT32_MAX && + aRange.location >= mIMECompositionStart && + aRange.location + aRange.length <= + mIMECompositionStart + compositionLength) { + NSRange range = + NSMakeRange(aRange.location - mIMECompositionStart, aRange.length); NSString* nsstr = [mIMECompositionString substringWithRange:range]; NSMutableAttributedString* result = - [[[NSMutableAttributedString alloc] initWithString:nsstr attributes:nil] autorelease]; + [[[NSMutableAttributedString alloc] initWithString:nsstr + attributes:nil] autorelease]; // XXX We cannot return font information in this case. However, this // case must occur only when IME tries to confirm if composing string // is handled as expected. @@ -4046,7 +4288,8 @@ NSAttributedString* IMEInputHandler::GetAttributedSubstringFromRange(NSRange& aR } nsAutoString str; - WidgetQueryContentEvent queryTextContentEvent(true, eQueryTextContent, mWidget); + WidgetQueryContentEvent queryTextContentEvent(true, eQueryTextContent, + mWidget); WidgetQueryContentEvent::Options options; int64_t startOffset = aRange.location; if (IsIMEComposing()) { @@ -4058,7 +4301,8 @@ NSAttributedString* IMEInputHandler::GetAttributedSubstringFromRange(NSRange& aR options.mRelativeToInsertionPoint = true; startOffset -= mIMECompositionStart; } - queryTextContentEvent.InitForQueryTextContent(startOffset, aRange.length, options); + queryTextContentEvent.InitForQueryTextContent(startOffset, aRange.length, + options); queryTextContentEvent.RequestFontRanges(); DispatchEvent(queryTextContentEvent); @@ -4073,11 +4317,14 @@ NSAttributedString* IMEInputHandler::GetAttributedSubstringFromRange(NSRange& aR // We don't set vertical information at this point. If required, // OS will calls drawsVerticallyForCharacterAtIndex. - NSMutableAttributedString* result = nsCocoaUtils::GetNSMutableAttributedString( - queryTextContentEvent.mReply->DataRef(), queryTextContentEvent.mReply->mFontRanges, false, - mWidget->BackingScaleFactor()); + NSMutableAttributedString* result = + nsCocoaUtils::GetNSMutableAttributedString( + queryTextContentEvent.mReply->DataRef(), + queryTextContentEvent.mReply->mFontRanges, false, + mWidget->BackingScaleFactor()); if (aActualRange) { - *aActualRange = MakeNSRangeFrom(queryTextContentEvent.mReply->mOffsetAndData); + *aActualRange = + MakeNSRangeFrom(queryTextContentEvent.mReply->mOffsetAndData); } return result; @@ -4110,11 +4357,13 @@ NSRange IMEInputHandler::MarkedRange() { NSRange IMEInputHandler::SelectedRange() { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::SelectedRange, Destroyed()=%s, mSelectedRange={ " - "location=%lu, length=%lu }", - this, TrueOrFalse(Destroyed()), static_cast(mSelectedRange.location), - static_cast(mSelectedRange.length))); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::SelectedRange, Destroyed()=%s, mSelectedRange={ " + "location=%lu, length=%lu }", + this, TrueOrFalse(Destroyed()), + static_cast(mSelectedRange.location), + static_cast(mSelectedRange.length))); if (Destroyed()) { return mSelectedRange; @@ -4127,19 +4376,22 @@ NSRange IMEInputHandler::SelectedRange() { RefPtr kungFuDeathGrip(this); - WidgetQueryContentEvent querySelectedTextEvent(true, eQuerySelectedText, mWidget); + WidgetQueryContentEvent querySelectedTextEvent(true, eQuerySelectedText, + mWidget); DispatchEvent(querySelectedTextEvent); MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::SelectedRange, querySelectedTextEvent={ mReply=%s }", this, - ToString(querySelectedTextEvent.mReply).c_str())); + ("%p IMEInputHandler::SelectedRange, querySelectedTextEvent={ " + "mReply=%s }", + this, ToString(querySelectedTextEvent.mReply).c_str())); if (querySelectedTextEvent.Failed()) { return mSelectedRange; } mWritingMode = querySelectedTextEvent.mReply->WritingModeRef(); - mRangeForWritingMode = MakeNSRangeFrom(querySelectedTextEvent.mReply->mOffsetAndData); + mRangeForWritingMode = + MakeNSRangeFrom(querySelectedTextEvent.mReply->mOffsetAndData); if (mIMEHasFocus) { mSelectedRange = mRangeForWritingMode; @@ -4163,14 +4415,16 @@ bool IMEInputHandler::DrawsVerticallyForCharacterAtIndex(uint32_t aCharIndex) { } if (aCharIndex < mRangeForWritingMode.location || - aCharIndex > mRangeForWritingMode.location + mRangeForWritingMode.length) { + aCharIndex > + mRangeForWritingMode.location + mRangeForWritingMode.length) { // It's not clear to me whether this ever happens in practice, but if an // IME ever wants to query writing mode at an offset outside the current // selection, the writing-mode value may not be correct for the index. // In that case, use FirstRectForCharacterRange to get a fresh value. - // This does more work than strictly necessary (we don't need the rect here), - // but should be a rare case. - NS_WARNING("DrawsVerticallyForCharacterAtIndex not using cached writing mode"); + // This does more work than strictly necessary (we don't need the rect + // here), but should be a rare case. + NS_WARNING( + "DrawsVerticallyForCharacterAtIndex not using cached writing mode"); NSRange range = NSMakeRange(aCharIndex, 1); NSRange actualRange; FirstRectForCharacterRange(range, &actualRange); @@ -4181,13 +4435,15 @@ bool IMEInputHandler::DrawsVerticallyForCharacterAtIndex(uint32_t aCharIndex) { NS_OBJC_END_TRY_BLOCK_RETURN(false); } -NSRect IMEInputHandler::FirstRectForCharacterRange(NSRange& aRange, NSRange* aActualRange) { +NSRect IMEInputHandler::FirstRectForCharacterRange(NSRange& aRange, + NSRange* aActualRange) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; MOZ_LOG(gIMELog, LogLevel::Info, ("%p IMEInputHandler::FirstRectForCharacterRange, Destroyed()=%s, " "aRange={ location=%lu, length=%lu }, aActualRange=%p }", - this, TrueOrFalse(Destroyed()), static_cast(aRange.location), + this, TrueOrFalse(Destroyed()), + static_cast(aRange.location), static_cast(aRange.length), aActualRange)); // XXX this returns first character rect or caret rect, it is limitation of @@ -4257,8 +4513,10 @@ NSRect IMEInputHandler::FirstRectForCharacterRange(NSRange& aRange, NSRange* aAc } nsIWidget* rootWidget = mWidget->GetTopLevelWidget(); - NSWindow* rootWindow = static_cast(rootWidget->GetNativeData(NS_NATIVE_WINDOW)); - NSView* rootView = static_cast(rootWidget->GetNativeData(NS_NATIVE_WIDGET)); + NSWindow* rootWindow = + static_cast(rootWidget->GetNativeData(NS_NATIVE_WINDOW)); + NSView* rootView = + static_cast(rootWidget->GetNativeData(NS_NATIVE_WIDGET)); if (!rootWindow || !rootView) { return rect; } @@ -4274,8 +4532,9 @@ NSRect IMEInputHandler::FirstRectForCharacterRange(NSRange& aRange, NSRange* aAc ("%p IMEInputHandler::FirstRectForCharacterRange, " "useCaretRect=%s rect={ x=%f, y=%f, width=%f, height=%f }, " "actualRange={ location=%lu, length=%lu }", - this, TrueOrFalse(useCaretRect), rect.origin.x, rect.origin.y, rect.size.width, - rect.size.height, static_cast(actualRange.location), + this, TrueOrFalse(useCaretRect), rect.origin.x, rect.origin.y, + rect.size.width, rect.size.height, + static_cast(actualRange.location), static_cast(actualRange.length))); return rect; @@ -4287,15 +4546,16 @@ NSUInteger IMEInputHandler::CharacterIndexForPoint(NSPoint& aPoint) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::CharacterIndexForPoint, aPoint={ x=%f, y=%f }", this, aPoint.x, - aPoint.y)); + ("%p IMEInputHandler::CharacterIndexForPoint, aPoint={ x=%f, y=%f }", + this, aPoint.x, aPoint.y)); NSWindow* mainWindow = [NSApp mainWindow]; if (!mWidget || !mainWindow) { return NSNotFound; } - WidgetQueryContentEvent queryCharAtPointEvent(true, eQueryCharacterAtPoint, mWidget); + WidgetQueryContentEvent queryCharAtPointEvent(true, eQueryCharacterAtPoint, + mWidget); NSPoint ptInWindow = nsCocoaUtils::ConvertPointFromScreen(mainWindow, aPoint); NSPoint ptInView = [mView convertPoint:ptInWindow fromView:nil]; queryCharAtPointEvent.mRefPoint.x = @@ -4303,8 +4563,10 @@ NSUInteger IMEInputHandler::CharacterIndexForPoint(NSPoint& aPoint) { queryCharAtPointEvent.mRefPoint.y = static_cast(ptInView.y * mWidget->BackingScaleFactor()); mWidget->DispatchWindowEvent(queryCharAtPointEvent); - if (queryCharAtPointEvent.Failed() || queryCharAtPointEvent.DidNotFindChar() || - queryCharAtPointEvent.mReply->StartOffset() >= static_cast(NSNotFound)) { + if (queryCharAtPointEvent.Failed() || + queryCharAtPointEvent.DidNotFindChar() || + queryCharAtPointEvent.mReply->StartOffset() >= + static_cast(NSNotFound)) { return NSNotFound; } @@ -4320,16 +4582,19 @@ extern NSString* NSTextInputReplacementRangeAttributeName; NSArray* IMEInputHandler::GetValidAttributesForMarkedText() { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - MOZ_LOG(gIMELog, LogLevel::Info, ("%p IMEInputHandler::GetValidAttributesForMarkedText", this)); + MOZ_LOG(gIMELog, LogLevel::Info, + ("%p IMEInputHandler::GetValidAttributesForMarkedText", this)); // Return same attributes as Chromium (see render_widget_host_view_mac.mm) // because most IMEs must be tested with Safari (OS default) and Chrome // (having most market share). Therefore, we need to follow their behavior. // XXX It might be better to reuse an array instance for this result because // this may be called a lot. Note that Chromium does so. - return [NSArray arrayWithObjects:NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName, - NSMarkedClauseSegmentAttributeName, - NSTextInputReplacementRangeAttributeName, nil]; + return + [NSArray arrayWithObjects:NSUnderlineStyleAttributeName, + NSUnderlineColorAttributeName, + NSMarkedClauseSegmentAttributeName, + NSTextInputReplacementRangeAttributeName, nil]; NS_OBJC_END_TRY_BLOCK_RETURN(nil); } @@ -4342,7 +4607,8 @@ NSArray* IMEInputHandler::GetValidAttributesForMarkedText() { * ******************************************************************************/ -IMEInputHandler::IMEInputHandler(nsChildView* aWidget, NSView* aNativeView) +IMEInputHandler::IMEInputHandler(nsChildView* aWidget, + NSView* aNativeView) : TextInputHandlerBase(aWidget, aNativeView), mPendingMethods(0), mIMECompositionString(nullptr), @@ -4377,10 +4643,12 @@ IMEInputHandler::~IMEInputHandler() { } void IMEInputHandler::OnFocusChangeInGecko(bool aFocus) { - MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::OnFocusChangeInGecko, aFocus=%s, Destroyed()=%s, " - "sFocusedIMEHandler=%p", - this, TrueOrFalse(aFocus), TrueOrFalse(Destroyed()), sFocusedIMEHandler)); + MOZ_LOG( + gIMELog, LogLevel::Info, + ("%p IMEInputHandler::OnFocusChangeInGecko, aFocus=%s, Destroyed()=%s, " + "sFocusedIMEHandler=%p", + this, TrueOrFalse(aFocus), TrueOrFalse(Destroyed()), + sFocusedIMEHandler)); mSelectedRange.location = NSNotFound; // Marking dirty mIMEHasFocus = aFocus; @@ -4404,7 +4672,8 @@ bool IMEInputHandler::OnDestroyWidget(nsChildView* aDestroyingWidget) { MOZ_LOG(gIMELog, LogLevel::Info, ("%p IMEInputHandler::OnDestroyWidget, aDestroyingWidget=%p, " "sFocusedIMEHandler=%p, IsIMEComposing()=%s", - this, aDestroyingWidget, sFocusedIMEHandler, TrueOrFalse(IsIMEComposing()))); + this, aDestroyingWidget, sFocusedIMEHandler, + TrueOrFalse(IsIMEComposing()))); // If we're not focused, the focused IMEInputHandler may have been // created by another widget/nsChildView. @@ -4430,11 +4699,11 @@ bool IMEInputHandler::OnDestroyWidget(nsChildView* aDestroyingWidget) { void IMEInputHandler::SendCommittedText(NSString* aString) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - MOZ_LOG( - gIMELog, LogLevel::Info, - ("%p IMEInputHandler::SendCommittedText, mView=%p, mWidget=%p, " - "inputContext=%p, mIsIMEComposing=%s", - this, mView, mWidget, mView ? [mView inputContext] : nullptr, TrueOrFalse(mIsIMEComposing))); + MOZ_LOG(gIMELog, LogLevel::Info, + ("%p IMEInputHandler::SendCommittedText, mView=%p, mWidget=%p, " + "inputContext=%p, mIsIMEComposing=%s", + this, mView, mWidget, mView ? [mView inputContext] : nullptr, + TrueOrFalse(mIsIMEComposing))); NS_ENSURE_TRUE(mWidget, ); // XXX We should send the string without mView. @@ -4442,10 +4711,13 @@ void IMEInputHandler::SendCommittedText(NSString* aString) { return; } - NSAttributedString* attrStr = [[NSAttributedString alloc] initWithString:aString]; + NSAttributedString* attrStr = + [[NSAttributedString alloc] initWithString:aString]; if ([mView conformsToProtocol:@protocol(NSTextInputClient)]) { - NSObject* textInputClient = static_cast*>(mView); - [textInputClient insertText:attrStr replacementRange:NSMakeRange(NSNotFound, 0)]; + NSObject* textInputClient = + static_cast*>(mView); + [textInputClient insertText:attrStr + replacementRange:NSMakeRange(NSNotFound, 0)]; } // Last resort. If we cannot retrieve NSTextInputProtocol from mView @@ -4453,7 +4725,8 @@ void IMEInputHandler::SendCommittedText(NSString* aString) { // directly to commit composition forcibly. if (mIsIMEComposing) { MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::SendCommittedText, trying to insert text directly " + ("%p IMEInputHandler::SendCommittedText, trying to insert text " + "directly " "due to IME not calling our InsertText()", this)); static_cast(this)->InsertText(attrStr); @@ -4473,7 +4746,8 @@ void IMEInputHandler::KillIMEComposition() { "inputContext=%p, mIsIMEComposing=%s, " "Destroyed()=%s, IsFocused()=%s", this, mView, mWidget, mView ? [mView inputContext] : nullptr, - TrueOrFalse(mIsIMEComposing), TrueOrFalse(Destroyed()), TrueOrFalse(IsFocused()))); + TrueOrFalse(mIsIMEComposing), TrueOrFalse(Destroyed()), + TrueOrFalse(IsFocused()))); if (Destroyed() || NS_WARN_IF(!mView)) { return; @@ -4492,8 +4766,8 @@ void IMEInputHandler::CommitIMEComposition() { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::CommitIMEComposition, mIMECompositionString=%s", this, - GetCharacters(mIMECompositionString))); + ("%p IMEInputHandler::CommitIMEComposition, mIMECompositionString=%s", + this, GetCharacters(mIMECompositionString))); // If this is called before dispatching eCompositionStart, IsIMEComposing() // returns false. Even in such case, we need to commit composition *in* @@ -4517,8 +4791,8 @@ void IMEInputHandler::CancelIMEComposition() { if (!IsIMEComposing()) return; MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::CancelIMEComposition, mIMECompositionString=%s", this, - GetCharacters(mIMECompositionString))); + ("%p IMEInputHandler::CancelIMEComposition, mIMECompositionString=%s", + this, GetCharacters(mIMECompositionString))); // For canceling the current composing, we need to ignore the param of // insertText. But this code is ugly... @@ -4599,24 +4873,29 @@ void IMEInputHandler::SetIMEOpenState(bool aOpenIME) { } void IMEInputHandler::OpenSystemPreferredLanguageIME() { - MOZ_LOG(gIMELog, LogLevel::Info, ("%p IMEInputHandler::OpenSystemPreferredLanguageIME", this)); + MOZ_LOG(gIMELog, LogLevel::Info, + ("%p IMEInputHandler::OpenSystemPreferredLanguageIME", this)); CFArrayRef langList = ::CFLocaleCopyPreferredLanguages(); if (!langList) { MOZ_LOG(gIMELog, LogLevel::Info, - ("%p IMEInputHandler::OpenSystemPreferredLanguageIME, langList is NULL", this)); + ("%p IMEInputHandler::OpenSystemPreferredLanguageIME, langList " + "is NULL", + this)); return; } CFIndex count = ::CFArrayGetCount(langList); for (CFIndex i = 0; i < count; i++) { CFLocaleRef locale = ::CFLocaleCreate( - kCFAllocatorDefault, static_cast(::CFArrayGetValueAtIndex(langList, i))); + kCFAllocatorDefault, + static_cast(::CFArrayGetValueAtIndex(langList, i))); if (!locale) { continue; } bool changed = false; - CFStringRef lang = static_cast(::CFLocaleGetValue(locale, kCFLocaleLanguageCode)); + CFStringRef lang = static_cast( + ::CFLocaleGetValue(locale, kCFLocaleLanguageCode)); NS_ASSERTION(lang, "lang is null"); if (lang) { TISInputSourceWrapper tis; @@ -4642,9 +4921,11 @@ void IMEInputHandler::OpenSystemPreferredLanguageIME() { ::CFRelease(langList); } -void IMEInputHandler::OnSelectionChange(const IMENotification& aIMENotification) { +void IMEInputHandler::OnSelectionChange( + const IMENotification& aIMENotification) { MOZ_ASSERT(aIMENotification.mSelectionChangeData.IsInitialized()); - MOZ_LOG(gIMELog, LogLevel::Info, ("%p IMEInputHandler::OnSelectionChange", this)); + MOZ_LOG(gIMELog, LogLevel::Info, + ("%p IMEInputHandler::OnSelectionChange", this)); if (!aIMENotification.mSelectionChangeData.HasRange()) { mSelectedRange.location = NSNotFound; @@ -4655,8 +4936,9 @@ void IMEInputHandler::OnSelectionChange(const IMENotification& aIMENotification) } mWritingMode = aIMENotification.mSelectionChangeData.GetWritingMode(); - mRangeForWritingMode = NSMakeRange(aIMENotification.mSelectionChangeData.mOffset, - aIMENotification.mSelectionChangeData.Length()); + mRangeForWritingMode = + NSMakeRange(aIMENotification.mSelectionChangeData.mOffset, + aIMENotification.mSelectionChangeData.Length()); if (mIMEHasFocus) { mSelectedRange = mRangeForWritingMode; } @@ -4696,7 +4978,8 @@ bool IMEInputHandler::OnHandleEvent(NSEvent* aEvent) { tis.InitByCurrentInputSource(); nsAutoString inputSourceID; tis.GetInputSourceID(inputSourceID); - allowConsumeEvent = !StringBeginsWith(inputSourceID, u"com.apple.inputmethod.Korean."_ns); + allowConsumeEvent = + !StringBeginsWith(inputSourceID, u"com.apple.inputmethod.Korean."_ns); } NSTextInputContext* inputContext = [mView inputContext]; return [inputContext handleEvent:aEvent] && allowConsumeEvent; @@ -4712,9 +4995,11 @@ bool IMEInputHandler::OnHandleEvent(NSEvent* aEvent) { int32_t TextInputHandlerBase::sSecureEventInputCount = 0; -NS_IMPL_ISUPPORTS(TextInputHandlerBase, TextEventDispatcherListener, nsISupportsWeakReference) +NS_IMPL_ISUPPORTS(TextInputHandlerBase, TextEventDispatcherListener, + nsISupportsWeakReference) -TextInputHandlerBase::TextInputHandlerBase(nsChildView* aWidget, NSView* aNativeView) +TextInputHandlerBase::TextInputHandlerBase(nsChildView* aWidget, + NSView* aNativeView) : mWidget(aWidget), mDispatcher(aWidget->GetTextEventDispatcher()) { gHandlerInstanceCount++; mView = [aNativeView retain]; @@ -4728,9 +5013,10 @@ TextInputHandlerBase::~TextInputHandlerBase() { } bool TextInputHandlerBase::OnDestroyWidget(nsChildView* aDestroyingWidget) { - MOZ_LOG_KEY_OR_IME(LogLevel::Info, ("%p TextInputHandlerBase::OnDestroyWidget, " - "aDestroyingWidget=%p, mWidget=%p", - this, aDestroyingWidget, mWidget)); + MOZ_LOG_KEY_OR_IME(LogLevel::Info, + ("%p TextInputHandlerBase::OnDestroyWidget, " + "aDestroyingWidget=%p, mWidget=%p", + this, aDestroyingWidget, mWidget)); if (aDestroyingWidget != mWidget) { return false; @@ -4745,46 +5031,53 @@ bool TextInputHandlerBase::DispatchEvent(WidgetGUIEvent& aEvent) { return mWidget->DispatchWindowEvent(aEvent); } -void TextInputHandlerBase::InitKeyEvent(NSEvent* aNativeKeyEvent, WidgetKeyboardEvent& aKeyEvent, - bool aIsProcessedByIME, const nsAString* aInsertString) { +void TextInputHandlerBase::InitKeyEvent(NSEvent* aNativeKeyEvent, + WidgetKeyboardEvent& aKeyEvent, + bool aIsProcessedByIME, + const nsAString* aInsertString) { NS_ASSERTION(aNativeKeyEvent, "aNativeKeyEvent must not be NULL"); if (mKeyboardOverride.mOverrideEnabled) { TISInputSourceWrapper tis; tis.InitByLayoutID(mKeyboardOverride.mKeyboardLayout, true); - tis.InitKeyEvent(aNativeKeyEvent, aKeyEvent, aIsProcessedByIME, aInsertString); + tis.InitKeyEvent(aNativeKeyEvent, aKeyEvent, aIsProcessedByIME, + aInsertString); return; } - TISInputSourceWrapper::CurrentInputSource().InitKeyEvent(aNativeKeyEvent, aKeyEvent, - aIsProcessedByIME, aInsertString); + TISInputSourceWrapper::CurrentInputSource().InitKeyEvent( + aNativeKeyEvent, aKeyEvent, aIsProcessedByIME, aInsertString); } -nsresult TextInputHandlerBase::SynthesizeNativeKeyEvent(int32_t aNativeKeyboardLayout, - int32_t aNativeKeyCode, - uint32_t aModifierFlags, - const nsAString& aCharacters, - const nsAString& aUnmodifiedCharacters) { +nsresult TextInputHandlerBase::SynthesizeNativeKeyEvent( + int32_t aNativeKeyboardLayout, int32_t aNativeKeyCode, + uint32_t aModifierFlags, const nsAString& aCharacters, + const nsAString& aUnmodifiedCharacters) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - uint32_t modifierFlags = nsCocoaUtils::ConvertWidgetModifiersToMacModifierFlags( - static_cast(aModifierFlags)); + uint32_t modifierFlags = + nsCocoaUtils::ConvertWidgetModifiersToMacModifierFlags( + static_cast(aModifierFlags)); NSInteger windowNumber = [[mView window] windowNumber]; bool sendFlagsChangedEvent = IsModifierKey(aNativeKeyCode); - NSEventType eventType = sendFlagsChangedEvent ? NSEventTypeFlagsChanged : NSEventTypeKeyDown; - NSEvent* downEvent = [NSEvent keyEventWithType:eventType - location:NSMakePoint(0, 0) - modifierFlags:modifierFlags - timestamp:0 - windowNumber:windowNumber - context:nil - characters:nsCocoaUtils::ToNSString(aCharacters) - charactersIgnoringModifiers:nsCocoaUtils::ToNSString(aUnmodifiedCharacters) - isARepeat:NO - keyCode:aNativeKeyCode]; + NSEventType eventType = + sendFlagsChangedEvent ? NSEventTypeFlagsChanged : NSEventTypeKeyDown; + NSEvent* downEvent = + [NSEvent keyEventWithType:eventType + location:NSMakePoint(0, 0) + modifierFlags:modifierFlags + timestamp:0 + windowNumber:windowNumber + context:nil + characters:nsCocoaUtils::ToNSString(aCharacters) + charactersIgnoringModifiers:nsCocoaUtils::ToNSString( + aUnmodifiedCharacters) + isARepeat:NO + keyCode:aNativeKeyCode]; NSEvent* upEvent = sendFlagsChangedEvent ? nil - : nsCocoaUtils::MakeNewCocoaEventWithType(NSEventTypeKeyUp, downEvent); + : nsCocoaUtils::MakeNewCocoaEventWithType( + NSEventTypeKeyUp, downEvent); if (downEvent && (sendFlagsChangedEvent || upEvent)) { KeyboardLayoutOverride currentLayout = mKeyboardOverride; @@ -4807,23 +5100,26 @@ nsresult TextInputHandlerBase::SynthesizeNativeKeyEvent(int32_t aNativeKeyboardL NSInteger TextInputHandlerBase::GetWindowLevel() { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - MOZ_LOG_KEY_OR_IME(LogLevel::Info, ("%p TextInputHandlerBase::GetWindowLevel, Destryoed()=%s", - this, TrueOrFalse(Destroyed()))); + MOZ_LOG_KEY_OR_IME(LogLevel::Info, + ("%p TextInputHandlerBase::GetWindowLevel, Destryoed()=%s", + this, TrueOrFalse(Destroyed()))); if (Destroyed()) { return NSNormalWindowLevel; } - // When an element on a XUL is focused, the actual focused view - // is the panel's parent view (mView). But the editor is displayed on the + // When an element on a XUL is focused, the actual focused + // view is the panel's parent view (mView). But the editor is displayed on the // popped-up widget's view (editorView). We want the latter's window level. NSView* editorView = mWidget->GetEditorView(); NS_ENSURE_TRUE(editorView, NSNormalWindowLevel); NSInteger windowLevel = [[editorView window] level]; - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandlerBase::GetWindowLevel, windowLevel=%s (%lX)", this, - GetWindowLevelName(windowLevel), static_cast(windowLevel))); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandlerBase::GetWindowLevel, windowLevel=%s (%lX)", this, + GetWindowLevelName(windowLevel), + static_cast(windowLevel))); return windowLevel; @@ -4840,15 +5136,16 @@ TextInputHandlerBase::AttachNativeKeyEvent(WidgetKeyboardEvent& aKeyEvent) { return NS_OK; } - MOZ_LOG_KEY_OR_IME(LogLevel::Info, - ("%p TextInputHandlerBase::AttachNativeKeyEvent, key=0x%X, char=0x%X, " - "mod=0x%X", - this, aKeyEvent.mKeyCode, aKeyEvent.mCharCode, aKeyEvent.mModifiers)); + MOZ_LOG_KEY_OR_IME( + LogLevel::Info, + ("%p TextInputHandlerBase::AttachNativeKeyEvent, key=0x%X, char=0x%X, " + "mod=0x%X", + this, aKeyEvent.mKeyCode, aKeyEvent.mCharCode, aKeyEvent.mModifiers)); NSInteger windowNumber = [[mView window] windowNumber]; NSGraphicsContext* context = [NSGraphicsContext currentContext]; - aKeyEvent.mNativeKeyEvent = - nsCocoaUtils::MakeNewCococaEventFromWidgetEvent(aKeyEvent, windowNumber, context); + aKeyEvent.mNativeKeyEvent = nsCocoaUtils::MakeNewCococaEventFromWidgetEvent( + aKeyEvent, windowNumber, context); return NS_OK; @@ -4873,7 +5170,8 @@ bool TextInputHandlerBase::SetSelection(NSRange& aRange) { return (aChar >= 0x20 && aChar <= 0x7E) || aChar >= 0xA0; } -/* static */ bool TextInputHandlerBase::IsSpecialGeckoKey(UInt32 aNativeKeyCode) { +/* static */ bool TextInputHandlerBase::IsSpecialGeckoKey( + UInt32 aNativeKeyCode) { // this table is used to determine which keys are special and should not // generate a charCode switch (aNativeKeyCode) { @@ -4937,15 +5235,18 @@ bool TextInputHandlerBase::SetSelection(NSRange& aRange) { return false; } -/* static */ bool TextInputHandlerBase::IsNormalCharInputtingEvent(NSEvent* aNativeEvent) { - if ([aNativeEvent type] != NSEventTypeKeyDown && [aNativeEvent type] != NSEventTypeKeyUp) { +/* static */ bool TextInputHandlerBase::IsNormalCharInputtingEvent( + NSEvent* aNativeEvent) { + if ([aNativeEvent type] != NSEventTypeKeyDown && + [aNativeEvent type] != NSEventTypeKeyUp) { return false; } nsAutoString nativeChars; nsCocoaUtils::GetStringForNSString([aNativeEvent characters], nativeChars); // this is not character inputting event, simply. - if (nativeChars.IsEmpty() || ([aNativeEvent modifierFlags] & NSEventModifierFlagCommand)) { + if (nativeChars.IsEmpty() || + ([aNativeEvent modifierFlags] & NSEventModifierFlagCommand)) { return false; } return !IsControlChar(nativeChars[0]); @@ -4991,9 +5292,9 @@ bool TextInputHandlerBase::SetSelection(NSRange& aRange) { // zero does not mean that Secure Input is _disabled_ because another // application may have enabled it. If the OS reports Secure Event // Input is disabled though, a non-zero sSecureEventInputCount is an error. - NS_ASSERTION( - ::IsSecureEventInputEnabled() || 0 == sSecureEventInputCount, - "sSecureEventInputCount is not zero when the OS thinks SecureEventInput is disabled."); + NS_ASSERTION(::IsSecureEventInputEnabled() || 0 == sSecureEventInputCount, + "sSecureEventInputCount is not zero when the OS thinks " + "SecureEventInput is disabled."); return !!sSecureEventInputCount; } @@ -5011,9 +5312,9 @@ bool TextInputHandlerBase::SetSelection(NSRange& aRange) { * ******************************************************************************/ -void TextInputHandlerBase::KeyEventState::InitKeyEvent(TextInputHandlerBase* aHandler, - WidgetKeyboardEvent& aKeyEvent, - bool aIsProcessedByIME) { +void TextInputHandlerBase::KeyEventState::InitKeyEvent( + TextInputHandlerBase* aHandler, WidgetKeyboardEvent& aKeyEvent, + bool aIsProcessedByIME) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; MOZ_ASSERT(aHandler); @@ -5027,25 +5328,28 @@ void TextInputHandlerBase::KeyEventState::InitKeyEvent(TextInputHandlerBase* aHa // If the key event's some characters were already handled by // InsertString() calls, we need to create a dummy event which doesn't // include the handled characters. - nativeEvent = [NSEvent keyEventWithType:[mKeyEvent type] - location:[mKeyEvent locationInWindow] - modifierFlags:[mKeyEvent modifierFlags] - timestamp:[mKeyEvent timestamp] - windowNumber:[mKeyEvent windowNumber] - context:nil - characters:unhandledNSString - charactersIgnoringModifiers:[mKeyEvent charactersIgnoringModifiers] - isARepeat:[mKeyEvent isARepeat] - keyCode:[mKeyEvent keyCode]]; + nativeEvent = + [NSEvent keyEventWithType:[mKeyEvent type] + location:[mKeyEvent locationInWindow] + modifierFlags:[mKeyEvent modifierFlags] + timestamp:[mKeyEvent timestamp] + windowNumber:[mKeyEvent windowNumber] + context:nil + characters:unhandledNSString + charactersIgnoringModifiers:[mKeyEvent charactersIgnoringModifiers] + isARepeat:[mKeyEvent isARepeat] + keyCode:[mKeyEvent keyCode]]; } aKeyEvent.mUniqueId = mUniqueId; - aHandler->InitKeyEvent(nativeEvent, aKeyEvent, aIsProcessedByIME, mInsertString); + aHandler->InitKeyEvent(nativeEvent, aKeyEvent, aIsProcessedByIME, + mInsertString); NS_OBJC_END_TRY_IGNORE_BLOCK; } -void TextInputHandlerBase::KeyEventState::GetUnhandledString(nsAString& aUnhandledString) const { +void TextInputHandlerBase::KeyEventState::GetUnhandledString( + nsAString& aUnhandledString) const { aUnhandledString.Truncate(); if (NS_WARN_IF(!mKeyEvent)) { return; @@ -5079,7 +5383,8 @@ TextInputHandlerBase::AutoInsertStringClearer::~AutoInsertStringClearer() { // If inserting string is a part of characters of the event, // we should record it as inserted string. nsAutoString characters; - nsCocoaUtils::GetStringForNSString([mState->mKeyEvent characters], characters); + nsCocoaUtils::GetStringForNSString([mState->mKeyEvent characters], + characters); nsAutoString insertedString(mState->mInsertedString); insertedString += *mState->mInsertString; if (StringBeginsWith(characters, insertedString)) { diff --git a/widget/cocoa/TextRecognition.mm b/widget/cocoa/TextRecognition.mm index 8b953473670c..c365f519826d 100644 --- a/widget/cocoa/TextRecognition.mm +++ b/widget/cocoa/TextRecognition.mm @@ -18,7 +18,8 @@ namespace mozilla::widget { auto TextRecognition::DoFindText(gfx::DataSourceSurface& aSurface, - const nsTArray& aLanguages) -> RefPtr { + const nsTArray& aLanguages) + -> RefPtr { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK // TODO - Is this the most efficient path? Maybe we can write a new @@ -26,7 +27,8 @@ auto TextRecognition::DoFindText(gfx::DataSourceSurface& aSurface, CGImageRef imageRef = NULL; nsresult rv = nsCocoaUtils::CreateCGImageFromSurface(&aSurface, &imageRef); if (NS_FAILED(rv) || !imageRef) { - return NativePromise::CreateAndReject("Failed to create CGImage"_ns, __func__); + return NativePromise::CreateAndReject("Failed to create CGImage"_ns, + __func__); } auto promise = MakeRefPtr(__func__); @@ -48,47 +50,63 @@ auto TextRecognition::DoFindText(gfx::DataSourceSurface& aSurface, dom::TextRecognitionResult result; dom::TextRecognitionResult* pResult = &result; - // Define the request to use, which also handles the result. It will be run below - // directly in this thread. After creating this request. - VNRecognizeTextRequest* textRecognitionRequest = [[VNRecognizeTextRequest alloc] - initWithCompletionHandler:^(VNRequest* _Nonnull request, NSError* _Nullable error) { - NSArray* observations = request.results; + // Define the request to use, which also handles the result. It will + // be run below directly in this thread. After creating this + // request. + VNRecognizeTextRequest* textRecognitionRequest = + [[VNRecognizeTextRequest alloc] initWithCompletionHandler:^( + VNRequest* _Nonnull request, + NSError* _Nullable error) { + NSArray* observations = + request.results; - [observations - enumerateObjectsUsingBlock:^(VNRecognizedTextObservation* _Nonnull obj, - NSUInteger idx, BOOL* _Nonnull stop) { - // Requests the n top candidates for a recognized text string. - VNRecognizedText* recognizedText = [obj topCandidates:1].firstObject; + [observations enumerateObjectsUsingBlock:^( + VNRecognizedTextObservation* _Nonnull obj, + NSUInteger idx, BOOL* _Nonnull stop) { + // Requests the n top candidates for a recognized text + // string. + VNRecognizedText* recognizedText = + [obj topCandidates:1].firstObject; - // https://developer.apple.com/documentation/vision/vnrecognizedtext?language=objc - auto& quad = *pResult->quads().AppendElement(); - CopyCocoaStringToXPCOMString(recognizedText.string, quad.string()); - quad.confidence() = recognizedText.confidence; + // https://developer.apple.com/documentation/vision/vnrecognizedtext?language=objc + auto& quad = *pResult->quads().AppendElement(); + CopyCocoaStringToXPCOMString(recognizedText.string, + quad.string()); + quad.confidence() = recognizedText.confidence; - auto ToImagePoint = [](CGPoint aPoint) -> ImagePoint { - return {static_cast(aPoint.x), static_cast(aPoint.y)}; - }; - *quad.points().AppendElement() = ToImagePoint(obj.bottomLeft); - *quad.points().AppendElement() = ToImagePoint(obj.topLeft); - *quad.points().AppendElement() = ToImagePoint(obj.topRight); - *quad.points().AppendElement() = ToImagePoint(obj.bottomRight); - }]; + auto ToImagePoint = [](CGPoint aPoint) -> ImagePoint { + return {static_cast(aPoint.x), + static_cast(aPoint.y)}; + }; + *quad.points().AppendElement() = + ToImagePoint(obj.bottomLeft); + *quad.points().AppendElement() = ToImagePoint(obj.topLeft); + *quad.points().AppendElement() = ToImagePoint(obj.topRight); + *quad.points().AppendElement() = + ToImagePoint(obj.bottomRight); + }]; }]; - textRecognitionRequest.recognitionLevel = VNRequestTextRecognitionLevelAccurate; + textRecognitionRequest.recognitionLevel = + VNRequestTextRecognitionLevelAccurate; textRecognitionRequest.recognitionLanguages = recognitionLanguages; textRecognitionRequest.usesLanguageCorrection = true; - // Send out the request. This blocks execution of this thread with an expensive - // CPU call. + // Send out the request. This blocks execution of this thread with + // an expensive CPU call. NSError* error = nil; VNImageRequestHandler* requestHandler = - [[[VNImageRequestHandler alloc] initWithCGImage:imageRef options:@{}] autorelease]; + [[[VNImageRequestHandler alloc] initWithCGImage:imageRef + options:@{}] + autorelease]; - [requestHandler performRequests:@[ textRecognitionRequest ] error:&error]; + [requestHandler performRequests:@[ textRecognitionRequest ] + error:&error]; if (error != nil) { promise->Reject( - nsPrintfCString("Failed to perform text recognition request (%ld)\n", error.code), + nsPrintfCString( + "Failed to perform text recognition request (%ld)\n", + error.code), __func__); } else { promise->Resolve(std::move(result), __func__); diff --git a/widget/cocoa/VibrancyManager.mm b/widget/cocoa/VibrancyManager.mm index d75725e1863b..2fce3f8728cc 100644 --- a/widget/cocoa/VibrancyManager.mm +++ b/widget/cocoa/VibrancyManager.mm @@ -16,27 +16,29 @@ using namespace mozilla; @interface MOZVibrantView : NSVisualEffectView { VibrancyType mType; } -- (instancetype)initWithFrame:(NSRect)aRect vibrancyType:(VibrancyType)aVibrancyType; +- (instancetype)initWithFrame:(NSRect)aRect + vibrancyType:(VibrancyType)aVibrancyType; @end @interface MOZVibrantLeafView : MOZVibrantView @end -static NSVisualEffectState VisualEffectStateForVibrancyType(VibrancyType aType) { +static NSVisualEffectState VisualEffectStateForVibrancyType( + VibrancyType aType) { switch (aType) { case VibrancyType::TOOLTIP: case VibrancyType::MENU: case VibrancyType::HIGHLIGHTED_MENUITEM: - // Tooltip and menu windows are never "key", so we need to tell the vibrancy effect to look - // active regardless of window state. + // Tooltip and menu windows are never "key", so we need to tell the + // vibrancy effect to look active regardless of window state. return NSVisualEffectStateActive; default: return NSVisualEffectStateFollowsWindowActiveState; } } -static NSVisualEffectMaterial VisualEffectMaterialForVibrancyType(VibrancyType aType, - BOOL* aOutIsEmphasized) { +static NSVisualEffectMaterial VisualEffectMaterialForVibrancyType( + VibrancyType aType, BOOL* aOutIsEmphasized) { switch (aType) { case VibrancyType::TOOLTIP: return (NSVisualEffectMaterial)NSVisualEffectMaterialToolTip; @@ -90,8 +92,8 @@ static NSVisualEffectMaterial VisualEffectMaterialForVibrancyType(VibrancyType a @end -bool VibrancyManager::UpdateVibrantRegion(VibrancyType aType, - const LayoutDeviceIntRegion& aRegion) { +bool VibrancyManager::UpdateVibrantRegion( + VibrancyType aType, const LayoutDeviceIntRegion& aRegion) { if (aRegion.IsEmpty()) { return mVibrantRegions.Remove(uint32_t(aType)); } @@ -109,7 +111,10 @@ LayoutDeviceIntRegion VibrancyManager::GetUnionOfVibrantRegions() const { return result; } -/* static */ NSView* VibrancyManager::CreateEffectView(VibrancyType aType, BOOL aIsContainer) { - return aIsContainer ? [[MOZVibrantView alloc] initWithFrame:NSZeroRect vibrancyType:aType] - : [[MOZVibrantLeafView alloc] initWithFrame:NSZeroRect vibrancyType:aType]; +/* static */ NSView* VibrancyManager::CreateEffectView(VibrancyType aType, + BOOL aIsContainer) { + return aIsContainer ? [[MOZVibrantView alloc] initWithFrame:NSZeroRect + vibrancyType:aType] + : [[MOZVibrantLeafView alloc] initWithFrame:NSZeroRect + vibrancyType:aType]; } diff --git a/widget/cocoa/ViewRegion.mm b/widget/cocoa/ViewRegion.mm index c99785f95626..62e76d2df8a5 100644 --- a/widget/cocoa/ViewRegion.mm +++ b/widget/cocoa/ViewRegion.mm @@ -18,7 +18,8 @@ ViewRegion::~ViewRegion() { } bool ViewRegion::UpdateRegion(const LayoutDeviceIntRegion& aRegion, - const nsChildView& aCoordinateConverter, NSView* aContainerView, + const nsChildView& aCoordinateConverter, + NSView* aContainerView, NSView* (^aViewCreationCallback)()) { if (mRegion == aRegion) { return false; @@ -33,7 +34,8 @@ bool ViewRegion::UpdateRegion(const LayoutDeviceIntRegion& aRegion, // The mViews array is now empty. size_t i = 0; - for (auto iter = aRegion.RectIter(); !iter.Done() || i < viewsToRecycle.Length(); i++) { + for (auto iter = aRegion.RectIter(); + !iter.Done() || i < viewsToRecycle.Length(); i++) { if (!iter.Done()) { NSView* view = nil; NSRect rect = aCoordinateConverter.DevPixelsToCocoaPoints(iter.Get()); diff --git a/widget/cocoa/nsAppShell.mm b/widget/cocoa/nsAppShell.mm index 98070a6090c5..e3fc4f14495e 100644 --- a/widget/cocoa/nsAppShell.mm +++ b/widget/cocoa/nsAppShell.mm @@ -57,7 +57,8 @@ using namespace mozilla; using namespace mozilla::widget; -#define WAKE_LOCK_LOG(...) MOZ_LOG(gMacWakeLockLog, mozilla::LogLevel::Debug, (__VA_ARGS__)) +#define WAKE_LOCK_LOG(...) \ + MOZ_LOG(gMacWakeLockLog, mozilla::LogLevel::Debug, (__VA_ARGS__)) static mozilla::LazyLogModule gMacWakeLockLog("MacWakeLock"); // A wake lock listener that disables screen saver when requested by @@ -74,24 +75,30 @@ class MacWakeLockListener final : public nsIDOMMozWakeLockListener { IOPMAssertionID mAssertionNoDisplaySleepID = kIOPMNullAssertionID; IOPMAssertionID mAssertionNoIdleSleepID = kIOPMNullAssertionID; - NS_IMETHOD Callback(const nsAString& aTopic, const nsAString& aState) override { + NS_IMETHOD Callback(const nsAString& aTopic, + const nsAString& aState) override { if (!aTopic.EqualsASCII("screen") && !aTopic.EqualsASCII("audio-playing") && !aTopic.EqualsASCII("video-playing")) { return NS_OK; } // we should still hold the lock for background audio. - if (aTopic.EqualsASCII("audio-playing") && aState.EqualsASCII("locked-background")) { + if (aTopic.EqualsASCII("audio-playing") && + aState.EqualsASCII("locked-background")) { WAKE_LOCK_LOG("keep audio playing even in background"); return NS_OK; } - bool shouldKeepDisplayOn = aTopic.EqualsASCII("screen") || aTopic.EqualsASCII("video-playing"); - CFStringRef assertionType = - shouldKeepDisplayOn ? kIOPMAssertionTypeNoDisplaySleep : kIOPMAssertionTypeNoIdleSleep; - IOPMAssertionID& assertionId = - shouldKeepDisplayOn ? mAssertionNoDisplaySleepID : mAssertionNoIdleSleepID; - WAKE_LOCK_LOG("topic=%s, state=%s, shouldKeepDisplayOn=%d", NS_ConvertUTF16toUTF8(aTopic).get(), + bool shouldKeepDisplayOn = + aTopic.EqualsASCII("screen") || aTopic.EqualsASCII("video-playing"); + CFStringRef assertionType = shouldKeepDisplayOn + ? kIOPMAssertionTypeNoDisplaySleep + : kIOPMAssertionTypeNoIdleSleep; + IOPMAssertionID& assertionId = shouldKeepDisplayOn + ? mAssertionNoDisplaySleepID + : mAssertionNoIdleSleepID; + WAKE_LOCK_LOG("topic=%s, state=%s, shouldKeepDisplayOn=%d", + NS_ConvertUTF16toUTF8(aTopic).get(), NS_ConvertUTF16toUTF8(aState).get(), shouldKeepDisplayOn); // Note the wake lock code ensures that we're not sent duplicate @@ -103,9 +110,10 @@ class MacWakeLockListener final : public nsIDOMMozWakeLockListener { } // Prevent screen saver. CFStringRef cf_topic = ::CFStringCreateWithCharacters( - kCFAllocatorDefault, reinterpret_cast(aTopic.Data()), aTopic.Length()); - IOReturn success = ::IOPMAssertionCreateWithName(assertionType, kIOPMAssertionLevelOn, - cf_topic, &assertionId); + kCFAllocatorDefault, reinterpret_cast(aTopic.Data()), + aTopic.Length()); + IOReturn success = ::IOPMAssertionCreateWithName( + assertionType, kIOPMAssertionLevelOn, cf_topic, &assertionId); CFRelease(cf_topic); if (success != kIOReturnSuccess) { WAKE_LOCK_LOG("failed to disable screensaver"); @@ -133,19 +141,21 @@ static bool gAppShellMethodsSwizzled = false; void OnUncaughtException(NSException* aException) { nsObjCExceptionLog(aException); - MOZ_CRASH("Uncaught Objective C exception from NSSetUncaughtExceptionHandler"); + MOZ_CRASH( + "Uncaught Objective C exception from NSSetUncaughtExceptionHandler"); } @implementation GeckoNSApplication -// Load is called very early during startup, when the Objective C runtime loads this class. +// Load is called very early during startup, when the Objective C runtime loads +// this class. + (void)load { NSSetUncaughtExceptionHandler(OnUncaughtException); } -// This method is called from NSDefaultTopLevelErrorHandler, which is invoked when an Objective C -// exception propagates up into the native event loop. It is possible that it is also called in -// other cases. +// This method is called from NSDefaultTopLevelErrorHandler, which is invoked +// when an Objective C exception propagates up into the native event loop. It is +// possible that it is also called in other cases. - (void)reportException:(NSException*)aException { if (ShouldIgnoreObjCException(aException)) { return; @@ -154,14 +164,16 @@ void OnUncaughtException(NSException* aException) { nsObjCExceptionLog(aException); #ifdef NIGHTLY_BUILD - MOZ_CRASH("Uncaught Objective C exception from -[GeckoNSApplication reportException:]"); + MOZ_CRASH("Uncaught Objective C exception from -[GeckoNSApplication " + "reportException:]"); #endif } - (void)sendEvent:(NSEvent*)anEvent { mozilla::BackgroundHangMonitor().NotifyActivity(); - if ([anEvent type] == NSEventTypeApplicationDefined && [anEvent subtype] == kEventSubtypeTrace) { + if ([anEvent type] == NSEventTypeApplicationDefined && + [anEvent subtype] == kEventSubtypeTrace) { mozilla::SignalTracerThread(); return; } @@ -208,7 +220,8 @@ void OnUncaughtException(NSException* aException) { NS_IMETHODIMP nsAppShell::ResumeNative(void) { nsresult retval = nsBaseAppShell::ResumeNative(); - if (NS_SUCCEEDED(retval) && (mSuspendNativeCount == 0) && mSkippedNativeCallback) { + if (NS_SUCCEEDED(retval) && (mSuspendNativeCount == 0) && + mSkippedNativeCallback) { mSkippedNativeCallback = false; ScheduleNativeEventCallback(); } @@ -243,11 +256,13 @@ nsAppShell::~nsAppShell() { if (mCFRunLoop) { if (mCFRunLoopSource) { - ::CFRunLoopRemoveSource(mCFRunLoop, mCFRunLoopSource, kCFRunLoopCommonModes); + ::CFRunLoopRemoveSource(mCFRunLoop, mCFRunLoopSource, + kCFRunLoopCommonModes); ::CFRelease(mCFRunLoopSource); } if (mCFRunLoopObserver) { - ::CFRunLoopRemoveObserver(mCFRunLoop, mCFRunLoopObserver, kCFRunLoopCommonModes); + ::CFRunLoopRemoveObserver(mCFRunLoop, mCFRunLoopObserver, + kCFRunLoopCommonModes); ::CFRelease(mCFRunLoopObserver); } ::CFRelease(mCFRunLoop); @@ -274,7 +289,8 @@ static void AddScreenWakeLockListener() { sWakeLockListener = new MacWakeLockListener(); sPowerManagerService->AddWakeLockListener(sWakeLockListener); } else { - NS_WARNING("Failed to retrieve PowerManagerService, wakelocks will be broken!"); + NS_WARNING( + "Failed to retrieve PowerManagerService, wakelocks will be broken!"); } } @@ -288,8 +304,8 @@ static void RemoveScreenWakeLockListener() { } } -void RunLoopObserverCallback(CFRunLoopObserverRef aObserver, CFRunLoopActivity aActivity, - void* aInfo) { +void RunLoopObserverCallback(CFRunLoopObserverRef aObserver, + CFRunLoopActivity aActivity, void* aInfo) { static_cast(aInfo)->OnRunLoopActivityChanged(aActivity); } @@ -298,30 +314,34 @@ void nsAppShell::OnRunLoopActivityChanged(CFRunLoopActivity aActivity) { mozilla::BackgroundHangMonitor().NotifyWait(); } - // When the event loop is in its waiting state, we would like the profiler to know that the thread - // is idle. The usual way to notify the profiler of idleness would be to place a profiler label - // frame with the IDLE category on the stack, for the duration of the function that does the - // waiting. However, since macOS uses an event loop model where "the event loop calls you", we do - // not control the function that does the waiting; the waiting happens inside CFRunLoop code. - // Instead, the run loop notifies us when it enters and exits the waiting state, by calling this - // function. - // So we do not have a function under our control that stays on the stack for the duration of the - // wait. So, rather than putting an AutoProfilerLabel on the stack, we will manually push and pop - // the label frame here. - // The location in the stack where this label frame is inserted is somewhat arbitrary. In - // practice, the label frame will be at the very tip of the stack, looking like it's "inside" the + // When the event loop is in its waiting state, we would like the profiler to + // know that the thread is idle. The usual way to notify the profiler of + // idleness would be to place a profiler label frame with the IDLE category on + // the stack, for the duration of the function that does the waiting. However, + // since macOS uses an event loop model where "the event loop calls you", we + // do not control the function that does the waiting; the waiting happens + // inside CFRunLoop code. Instead, the run loop notifies us when it enters and + // exits the waiting state, by calling this function. So we do not have a + // function under our control that stays on the stack for the duration of the + // wait. So, rather than putting an AutoProfilerLabel on the stack, we will + // manually push and pop the label frame here. The location in the stack where + // this label frame is inserted is somewhat arbitrary. In practice, the label + // frame will be at the very tip of the stack, looking like it's "inside" the // mach_msg_trap wait function. if (aActivity == kCFRunLoopBeforeWaiting) { using ThreadRegistration = mozilla::profiler::ThreadRegistration; - ThreadRegistration::WithOnThreadRef([&](ThreadRegistration::OnThreadRef aOnThreadRef) { - ProfilingStack& profilingStack = - aOnThreadRef.UnlockedConstReaderAndAtomicRWRef().ProfilingStackRef(); - mProfilingStackWhileWaiting = &profilingStack; - uint8_t variableOnStack = 0; - profilingStack.pushLabelFrame("Native event loop idle", nullptr, &variableOnStack, - JS::ProfilingCategoryPair::IDLE, 0); - profiler_thread_sleep(); - }); + ThreadRegistration::WithOnThreadRef( + [&](ThreadRegistration::OnThreadRef aOnThreadRef) { + ProfilingStack& profilingStack = + aOnThreadRef.UnlockedConstReaderAndAtomicRWRef() + .ProfilingStackRef(); + mProfilingStackWhileWaiting = &profilingStack; + uint8_t variableOnStack = 0; + profilingStack.pushLabelFrame("Native event loop idle", nullptr, + &variableOnStack, + JS::ProfilingCategoryPair::IDLE, 0); + profiler_thread_sleep(); + }); } else { if (mProfilingStackWhileWaiting) { mProfilingStackWhileWaiting->pop(); @@ -356,8 +376,9 @@ nsresult nsAppShell::Init() { mAutoreleasePools = ::CFArrayCreateMutable(nullptr, 0, nullptr); NS_ENSURE_STATE(mAutoreleasePools); - bool isNSApplicationProcessType = (XRE_GetProcessType() != GeckoProcessType_RDD) && - (XRE_GetProcessType() != GeckoProcessType_Socket); + bool isNSApplicationProcessType = + (XRE_GetProcessType() != GeckoProcessType_RDD) && + (XRE_GetProcessType() != GeckoProcessType_Socket); if (isNSApplicationProcessType) { // This call initializes NSApplication unless: @@ -391,14 +412,15 @@ nsresult nsAppShell::Init() { ::CFRunLoopAddSource(mCFRunLoop, mCFRunLoopSource, kCFRunLoopCommonModes); - // Add a CFRunLoopObserver so that the profiler can be notified when we enter and exit the waiting - // state. + // Add a CFRunLoopObserver so that the profiler can be notified when we enter + // and exit the waiting state. CFRunLoopObserverContext observerContext; PodZero(&observerContext); observerContext.info = this; mCFRunLoopObserver = ::CFRunLoopObserverCreate( - kCFAllocatorDefault, kCFRunLoopBeforeWaiting | kCFRunLoopAfterWaiting | kCFRunLoopExit, true, + kCFAllocatorDefault, + kCFRunLoopBeforeWaiting | kCFRunLoopAfterWaiting | kCFRunLoopExit, true, 0, RunLoopObserverCallback, &observerContext); NS_ENSURE_STATE(mCFRunLoopObserver); @@ -491,9 +513,10 @@ void nsAppShell::ProcessGeckoEvents(void* aInfo) { // DummyEvent inserted by nsBaseAppShell::OnProcessNextEvent. This second // event will cause the second call to AcquireFirstMatchingEventInQueue in // nsAppShell::ProcessNextNativeEvent to return true. Which makes - // nsBaseAppShell::OnProcessNextEvent call nsAppShell::ProcessNextNativeEvent - // again during which it will loop until it sleeps because ProcessGeckoEvents() - // won't be called for the DummyEvent. + // nsBaseAppShell::OnProcessNextEvent call + // nsAppShell::ProcessNextNativeEvent again during which it will loop until + // it sleeps because ProcessGeckoEvents() won't be called for the + // DummyEvent. // // This is not a good approach and we should fix things up so that only // one postEvent is needed. @@ -551,8 +574,8 @@ void nsAppShell::ProcessGeckoEvents(void* aInfo) { if (self->mTerminated) { int32_t releaseCount = 0; if (self->mNativeEventScheduledDepth > self->mNativeEventCallbackDepth) { - releaseCount = - PR_ATOMIC_SET(&self->mNativeEventScheduledDepth, self->mNativeEventCallbackDepth); + releaseCount = PR_ATOMIC_SET(&self->mNativeEventScheduledDepth, + self->mNativeEventCallbackDepth); } while (releaseCount-- > self->mNativeEventCallbackDepth) self->Release(); } else { @@ -651,10 +674,10 @@ bool nsAppShell::ProcessNextNativeEvent(bool aMayWait) { if (mTerminated) return false; - // Do not call -[NSApplication nextEventMatchingMask:...] when we're trying to close a native - // menu. Doing so could confuse the NSMenu's closing mechanism. Instead, we try to unwind the - // stack as quickly as possible and return to the parent event loop. At that point, native events - // will be processed. + // Do not call -[NSApplication nextEventMatchingMask:...] when we're trying to + // close a native menu. Doing so could confuse the NSMenu's closing mechanism. + // Instead, we try to unwind the stack as quickly as possible and return to + // the parent event loop. At that point, native events will be processed. if (MOZMenuOpeningCoordinator.needToUnwindForMenuClosing) { return false; } @@ -700,12 +723,13 @@ bool nsAppShell::ProcessNextNativeEvent(bool aMayWait) { } } else { // In at least 10.15, AcquireFirstMatchingEventInQueue will move 1 - // CGEvent from the CGEvent queue into the Carbon event queue. Unfortunately, - // once an event has been moved to the Carbon event queue it's no longer a - // candidate for coalescing. This means that even if we don't remove the - // event from the queue, just calling AcquireFirstMatchingEventInQueue can - // cause behaviour change. Prior to bug 1690687 landing, the event that we got - // from AcquireFirstMatchingEventInQueue was often our own ApplicationDefined + // CGEvent from the CGEvent queue into the Carbon event queue. + // Unfortunately, once an event has been moved to the Carbon event queue + // it's no longer a candidate for coalescing. This means that even if we + // don't remove the event from the queue, just calling + // AcquireFirstMatchingEventInQueue can cause behaviour change. Prior to + // bug 1690687 landing, the event that we got from + // AcquireFirstMatchingEventInQueue was often our own ApplicationDefined // event. However, once we stopped posting that event on every Gecko // event we're much more likely to get a CGEvent. When we have a high // amount of load on the main thread, we end up alternating between Gecko @@ -719,8 +743,8 @@ bool nsAppShell::ProcessNextNativeEvent(bool aMayWait) { // AcquireFirstMatchingEventInQueue() doesn't spin the (native) event // loop, though it does queue up any newly available events from the // window server. - EventRef currentEvent = - AcquireFirstMatchingEventInQueue(currentEventQueue, 0, NULL, kEventQueueOptionsNone); + EventRef currentEvent = AcquireFirstMatchingEventInQueue( + currentEventQueue, 0, NULL, kEventQueueOptionsNone); if (!currentEvent) { continue; } @@ -729,7 +753,8 @@ bool nsAppShell::ProcessNextNativeEvent(bool aMayWait) { UInt32 eventClass = GetEventClass(currentEvent); bool osCocoaEvent = ((eventClass == 'appl') || (eventClass == kEventClassAppleEvent) || - ((eventClass == 'cgs ') && (eventKind != NSEventTypeApplicationDefined))); + ((eventClass == 'cgs ') && + (eventKind != NSEventTypeApplicationDefined))); // If attrs is kEventAttributeUserEvent or kEventAttributeMonitored // (i.e. a user input event), we shouldn't process it here while // aMayWait is false. Likewise if currentEvent will eventually be @@ -761,8 +786,9 @@ bool nsAppShell::ProcessNextNativeEvent(bool aMayWait) { } while (mRunningEventLoop); if (eventProcessed) { - moreEvents = (AcquireFirstMatchingEventInQueue(currentEventQueue, 0, NULL, - kEventQueueOptionsNone) != NULL); + moreEvents = + (AcquireFirstMatchingEventInQueue(currentEventQueue, 0, NULL, + kEventQueueOptionsNone) != NULL); } mRunningEventLoop = wasRunningEventLoop; @@ -790,7 +816,9 @@ bool nsAppShell::ProcessNextNativeEvent(bool aMayWait) { // (Ventura) than on other versions of macOS. So we only use this hack on // macOS 13 and up. static void PinSidecarCoreTextCStringSections() { - if (!dlopen("/System/Library/PrivateFrameworks/SidecarCore.framework/SidecarCore", RTLD_LAZY)) { + if (!dlopen( + "/System/Library/PrivateFrameworks/SidecarCore.framework/SidecarCore", + RTLD_LAZY)) { return; } @@ -798,7 +826,8 @@ static void PinSidecarCoreTextCStringSections() { // normally runs automatically on the first Cmd-key combination. Class displayManagerClass = NSClassFromString(@"SidecarDisplayManager"); if ([displayManagerClass respondsToSelector:@selector(sharedManager)]) { - id sharedManager = [displayManagerClass performSelector:@selector(sharedManager)]; + id sharedManager = + [displayManagerClass performSelector:@selector(sharedManager)]; if ([sharedManager respondsToSelector:@selector(devices)]) { [sharedManager performSelector:@selector(devices)]; } @@ -877,7 +906,8 @@ nsAppShell::Exit(void) { // [NSApp stop:], so we have to assume that one extra call to [NSApp stop:] // will do the job.) BOOL cocoaModal = [NSApp _isRunningModal]; - NS_ASSERTION(!cocoaModal, "Don't call nsAppShell::Exit() from a modal event loop!"); + NS_ASSERTION(!cocoaModal, + "Don't call nsAppShell::Exit() from a modal event loop!"); if (cocoaModal) [NSApp stop:nullptr]; [NSApp stop:nullptr]; @@ -911,7 +941,8 @@ NS_IMETHODIMP nsAppShell::OnProcessNextEvent(nsIThreadInternal* aThread, bool aMayWait) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - NS_ASSERTION(mAutoreleasePools, "No stack on which to store autorelease pool"); + NS_ASSERTION(mAutoreleasePools, + "No stack on which to store autorelease pool"); NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; ::CFArrayAppendValue(mAutoreleasePools, pool); @@ -929,15 +960,17 @@ nsAppShell::OnProcessNextEvent(nsIThreadInternal* aThread, bool aMayWait) { // // public NS_IMETHODIMP -nsAppShell::AfterProcessNextEvent(nsIThreadInternal* aThread, bool aEventWasProcessed) { +nsAppShell::AfterProcessNextEvent(nsIThreadInternal* aThread, + bool aEventWasProcessed) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; CFIndex count = ::CFArrayGetCount(mAutoreleasePools); - NS_ASSERTION(mAutoreleasePools && count, "Processed an event, but there's no autorelease pool?"); + NS_ASSERTION(mAutoreleasePools && count, + "Processed an event, but there's no autorelease pool?"); - const NSAutoreleasePool* pool = - static_cast(::CFArrayGetValueAtIndex(mAutoreleasePools, count - 1)); + const NSAutoreleasePool* pool = static_cast( + ::CFArrayGetValueAtIndex(mAutoreleasePools, count - 1)); ::CFArrayRemoveValueAtIndex(mAutoreleasePools, count - 1); [pool release]; @@ -952,11 +985,11 @@ void nsAppShell::InitMemoryPressureObserver() { // values. Hence this may need to be augmented with polling of the memory // pressure sysctls for lower latency reactions to OS memory pressure. This // was also observed when using DISPATCH_QUEUE_PRIORITY_HIGH. - mMemoryPressureSource = - dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYPRESSURE, 0, - DISPATCH_MEMORYPRESSURE_NORMAL | DISPATCH_MEMORYPRESSURE_WARN | - DISPATCH_MEMORYPRESSURE_CRITICAL, - dispatch_get_main_queue()); + mMemoryPressureSource = dispatch_source_create( + DISPATCH_SOURCE_TYPE_MEMORYPRESSURE, 0, + DISPATCH_MEMORYPRESSURE_NORMAL | DISPATCH_MEMORYPRESSURE_WARN | + DISPATCH_MEMORYPRESSURE_CRITICAL, + dispatch_get_main_queue()); dispatch_source_set_event_handler(mMemoryPressureSource, ^{ dispatch_source_memorypressure_flags_t pressureLevel = @@ -971,7 +1004,8 @@ void nsAppShell::InitMemoryPressureObserver() { nsAvailableMemoryWatcherBase::GetSingleton()); } -void nsAppShell::OnMemoryPressureChanged(dispatch_source_memorypressure_flags_t aPressureLevel) { +void nsAppShell::OnMemoryPressureChanged( + dispatch_source_memorypressure_flags_t aPressureLevel) { // The memory pressure dispatch source is created (above) with // dispatch_get_main_queue() which always fires on the main thread. MOZ_ASSERT(NS_IsMainThread()); @@ -1008,18 +1042,21 @@ void nsAppShell::OnMemoryPressureChanged(dispatch_source_memorypressure_flags_t if ((self = [self init])) { mAppShell = aAppShell; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(applicationWillTerminate:) - name:NSApplicationWillTerminateNotification - object:NSApp]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(applicationDidBecomeActive:) - name:NSApplicationDidBecomeActiveNotification - object:NSApp]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(timezoneChanged:) - name:NSSystemTimeZoneDidChangeNotification - object:nil]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(applicationWillTerminate:) + name:NSApplicationWillTerminateNotification + object:NSApp]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(applicationDidBecomeActive:) + name:NSApplicationDidBecomeActiveNotification + object:NSApp]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(timezoneChanged:) + name:NSSystemTimeZoneDidChangeNotification + object:nil]; } return self; @@ -1061,12 +1098,14 @@ void nsAppShell::OnMemoryPressureChanged(dispatch_source_memorypressure_flags_t NSEvent* currentEvent = [NSApp currentEvent]; if (currentEvent) { TextInputHandler::sLastModifierState = - [currentEvent modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask; + [currentEvent modifierFlags] & + NSEventModifierFlagDeviceIndependentFlagsMask; } nsCOMPtr observerService = services::GetObserverService(); if (observerService) { - observerService->NotifyObservers(nullptr, NS_WIDGET_MAC_APP_ACTIVATE_OBSERVER_TOPIC, nullptr); + observerService->NotifyObservers( + nullptr, NS_WIDGET_MAC_APP_ACTIVATE_OBSERVER_TOPIC, nullptr); } NS_OBJC_END_TRY_IGNORE_BLOCK; @@ -1111,8 +1150,9 @@ void nsAppShell::OnMemoryPressureChanged(dispatch_source_memorypressure_flags_t // in XRE_Main(), which in particular means that ScopedXPCOMStartup's destructor // and NS_ShutdownXPCOM() never get called. - (void)nsAppShell_NSApplication_terminate:(id)sender { - [[NSNotificationCenter defaultCenter] postNotificationName:NSApplicationWillTerminateNotification - object:NSApp]; + [[NSNotificationCenter defaultCenter] + postNotificationName:NSApplicationWillTerminateNotification + object:NSApp]; } @end diff --git a/widget/cocoa/nsChildView.mm b/widget/cocoa/nsChildView.mm index 5dcd6b57345e..cae1fa49c785 100644 --- a/widget/cocoa/nsChildView.mm +++ b/widget/cocoa/nsChildView.mm @@ -138,7 +138,8 @@ CG_EXTERN void CGContextResetClip(CGContextRef); typedef CFTypeRef CGSRegionObj; CGError CGSNewRegionWithRect(const CGRect* rect, CGSRegionObj* outRegion); -CGError CGSNewRegionWithRectList(const CGRect* rects, int rectCount, CGSRegionObj* outRegion); +CGError CGSNewRegionWithRectList(const CGRect* rects, int rectCount, + CGSRegionObj* outRegion); } // defined in nsMenuBarX.mm @@ -164,7 +165,8 @@ static bool sIsTabletPointerActivated = false; static uint32_t sUniqueKeyEventId = 0; -// The view that will do our drawing or host our NSOpenGLContext or Core Animation layer. +// The view that will do our drawing or host our NSOpenGLContext or Core +// Animation layer. @interface PixelHostingView : NSView { } @@ -178,7 +180,8 @@ static uint32_t sUniqueKeyEventId = 0; // set up a gecko mouse event based on a cocoa mouse event - (void)convertCocoaMouseWheelEvent:(NSEvent*)aMouseEvent toGeckoEvent:(WidgetWheelEvent*)outWheelEvent; -- (void)convertCocoaMouseEvent:(NSEvent*)aMouseEvent toGeckoEvent:(WidgetInputEvent*)outGeckoEvent; +- (void)convertCocoaMouseEvent:(NSEvent*)aMouseEvent + toGeckoEvent:(WidgetInputEvent*)outGeckoEvent; - (void)convertCocoaTabletPointerEvent:(NSEvent*)aMouseEvent toGeckoEvent:(WidgetMouseEvent*)outGeckoEvent; - (NSMenu*)contextMenu; @@ -203,8 +206,9 @@ static uint32_t sUniqueKeyEventId = 0; #pragma mark - -// Flips a screen coordinate from a point in the cocoa coordinate system (bottom-left rect) to a -// point that is a "flipped" cocoa coordinate system (starts in the top-left). +// Flips a screen coordinate from a point in the cocoa coordinate system +// (bottom-left rect) to a point that is a "flipped" cocoa coordinate system +// (starts in the top-left). static inline void FlipCocoaScreenCoordinate(NSPoint& inPoint) { inPoint.y = nsCocoaUtils::FlippedScreenY(inPoint.y); } @@ -233,7 +237,9 @@ nsChildView::~nsChildView() { childView->ResetParent(); } - NS_WARNING_ASSERTION(mOnDestroyCalled, "nsChildView object destroyed without calling Destroy()"); + NS_WARNING_ASSERTION( + mOnDestroyCalled, + "nsChildView object destroyed without calling Destroy()"); if (mContentLayer) { mNativeLayerRoot->RemoveLayer(mContentLayer); // safe if already removed @@ -254,7 +260,8 @@ nsChildView::~nsChildView() { } nsresult nsChildView::Create(nsIWidget* aParent, nsNativeWidget aNativeParent, - const LayoutDeviceIntRect& aRect, widget::InitData* aInitData) { + const LayoutDeviceIntRect& aRect, + widget::InitData* aInitData) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; // Because the hidden window is created outside of an event loop, @@ -499,7 +506,8 @@ bool nsChildView::IsVisible() const { // private method -[NSWindow _setNeedsDisplayInRect:]. Our BaseWindow // implementation of that method is augmented to let us ignore those calls // using -[BaseWindow disable/enableSetNeedsDisplay]. -static void ManipulateViewWithoutNeedingDisplay(NSView* aView, void (^aCallback)()) { +static void ManipulateViewWithoutNeedingDisplay(NSView* aView, + void (^aCallback)()) { BaseWindow* win = nil; if ([[aView window] isKindOfClass:[BaseWindow class]]) { win = (BaseWindow*)[aView window]; @@ -564,7 +572,8 @@ void nsChildView::ReparentNativeWidget(nsIWidget* aNewParent) { if (mOnDestroyCalled) return; - NSView* newParentView = (NSView*)aNewParent->GetNativeData(NS_NATIVE_WIDGET); + NSView* newParentView = + (NSView*)aNewParent->GetNativeData(NS_NATIVE_WIDGET); NS_ENSURE_TRUE_VOID(newParentView); // we hold a ref to mView, so this is safe @@ -616,8 +625,9 @@ void nsChildView::SetCursor(const Cursor& aCursor) { nsBaseWidget::SetCursor(aCursor); - if (NS_SUCCEEDED([[nsCursorManager sharedInstance] setCustomCursor:aCursor - widgetScaleFactor:BackingScaleFactor()])) { + if (NS_SUCCEEDED([[nsCursorManager sharedInstance] + setCustomCursor:aCursor + widgetScaleFactor:BackingScaleFactor()])) { return; } @@ -738,7 +748,8 @@ void nsChildView::Resize(double aWidth, double aHeight, bool aRepaint) { NS_OBJC_END_TRY_IGNORE_BLOCK; } -void nsChildView::Resize(double aX, double aY, double aWidth, double aHeight, bool aRepaint) { +void nsChildView::Resize(double aX, double aY, double aWidth, double aHeight, + bool aRepaint) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; int32_t x = NSToIntRound(aX); @@ -789,17 +800,17 @@ void nsChildView::Resize(double aX, double aY, double aWidth, double aHeight, bo // different thread, the two will race to the window server and show up on the // screen in the order that they happen to arrive in at the window server. // When the window size changes, there's another event that needs to be -// synchronized with: the window "shape" change. Cocoa has built-in synchronization -// mechanics that make sure that *main thread* window paints during window resizes -// are synchronized properly with the window shape change. But no such built-in -// synchronization exists for CATransactions that are triggered on a non-main -// thread. -// To cope with this, we define a "danger zone" during which we simply avoid -// triggering any CATransactions on a non-main thread (called "async" CATransactions -// here). This danger zone starts at the earliest opportunity at which we know -// about the size change, which is nsChildView::Resize, and ends at a point at -// which we know for sure that the paint has been handled completely, which is -// when we return to the event loop after layer display. +// synchronized with: the window "shape" change. Cocoa has built-in +// synchronization mechanics that make sure that *main thread* window paints +// during window resizes are synchronized properly with the window shape change. +// But no such built-in synchronization exists for CATransactions that are +// triggered on a non-main thread. To cope with this, we define a "danger zone" +// during which we simply avoid triggering any CATransactions on a non-main +// thread (called "async" CATransactions here). This danger zone starts at the +// earliest opportunity at which we know about the size change, which is +// nsChildView::Resize, and ends at a point at which we know for sure that the +// paint has been handled completely, which is when we return to the event loop +// after layer display. void nsChildView::SuspendAsyncCATransactions() { if (mUnsuspendAsyncCATransactionsRunnable) { mUnsuspendAsyncCATransactionsRunnable->Cancel(); @@ -817,9 +828,9 @@ void nsChildView::SuspendAsyncCATransactions() { void nsChildView::MaybeScheduleUnsuspendAsyncCATransactions() { if (mNativeLayerRoot->AreOffMainThreadCommitsSuspended() && !mUnsuspendAsyncCATransactionsRunnable) { - mUnsuspendAsyncCATransactionsRunnable = - NewCancelableRunnableMethod("nsChildView::MaybeScheduleUnsuspendAsyncCATransactions", this, - &nsChildView::UnsuspendAsyncCATransactions); + mUnsuspendAsyncCATransactionsRunnable = NewCancelableRunnableMethod( + "nsChildView::MaybeScheduleUnsuspendAsyncCATransactions", this, + &nsChildView::UnsuspendAsyncCATransactions); NS_DispatchToMainThread(mUnsuspendAsyncCATransactionsRunnable); } } @@ -843,41 +854,45 @@ void nsChildView::UpdateFullscreen(bool aFullscreen) { } } -nsresult nsChildView::SynthesizeNativeKeyEvent(int32_t aNativeKeyboardLayout, - int32_t aNativeKeyCode, uint32_t aModifierFlags, - const nsAString& aCharacters, - const nsAString& aUnmodifiedCharacters, - nsIObserver* aObserver) { +nsresult nsChildView::SynthesizeNativeKeyEvent( + int32_t aNativeKeyboardLayout, int32_t aNativeKeyCode, + uint32_t aModifierFlags, const nsAString& aCharacters, + const nsAString& aUnmodifiedCharacters, nsIObserver* aObserver) { AutoObserverNotifier notifier(aObserver, "keyevent"); return mTextInputHandler->SynthesizeNativeKeyEvent( - aNativeKeyboardLayout, aNativeKeyCode, aModifierFlags, aCharacters, aUnmodifiedCharacters); + aNativeKeyboardLayout, aNativeKeyCode, aModifierFlags, aCharacters, + aUnmodifiedCharacters); } -nsresult nsChildView::SynthesizeNativeMouseEvent(LayoutDeviceIntPoint aPoint, - NativeMouseMessage aNativeMessage, - MouseButton aButton, - nsIWidget::Modifiers aModifierFlags, - nsIObserver* aObserver) { +nsresult nsChildView::SynthesizeNativeMouseEvent( + LayoutDeviceIntPoint aPoint, NativeMouseMessage aNativeMessage, + MouseButton aButton, nsIWidget::Modifiers aModifierFlags, + nsIObserver* aObserver) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; AutoObserverNotifier notifier(aObserver, "mouseevent"); - NSPoint pt = nsCocoaUtils::DevPixelsToCocoaPoints(aPoint, BackingScaleFactor()); + NSPoint pt = + nsCocoaUtils::DevPixelsToCocoaPoints(aPoint, BackingScaleFactor()); - // Move the mouse cursor to the requested position and reconnect it to the mouse. + // Move the mouse cursor to the requested position and reconnect it to the + // mouse. CGWarpMouseCursorPosition(NSPointToCGPoint(pt)); CGAssociateMouseAndMouseCursorPosition(true); // aPoint is given with the origin on the top left, but convertScreenToBase - // expects a point in a coordinate system that has its origin on the bottom left. + // expects a point in a coordinate system that has its origin on the bottom + // left. NSPoint screenPoint = NSMakePoint(pt.x, nsCocoaUtils::FlippedScreenY(pt.y)); - NSPoint windowPoint = nsCocoaUtils::ConvertPointFromScreen([mView window], screenPoint); + NSPoint windowPoint = + nsCocoaUtils::ConvertPointFromScreen([mView window], screenPoint); NSEventModifierFlags modifierFlags = nsCocoaUtils::ConvertWidgetModifiersToMacModifierFlags(aModifierFlags); if (aButton == MouseButton::eX1 || aButton == MouseButton::eX2) { - // NSEvent has `buttonNumber` for `NSEventTypeOther*`. However, it seems that - // there is no way to specify it. Therefore, we should return error for now. + // NSEvent has `buttonNumber` for `NSEventTypeOther*`. However, it seems + // that there is no way to specify it. Therefore, we should return error + // for now. return NS_ERROR_INVALID_ARG; } @@ -917,15 +932,16 @@ nsresult nsChildView::SynthesizeNativeMouseEvent(LayoutDeviceIntPoint aPoint, break; } - NSEvent* event = [NSEvent mouseEventWithType:nativeEventType - location:windowPoint - modifierFlags:modifierFlags - timestamp:[[NSProcessInfo processInfo] systemUptime] - windowNumber:[[mView window] windowNumber] - context:nil - eventNumber:0 - clickCount:1 - pressure:0.0]; + NSEvent* event = + [NSEvent mouseEventWithType:nativeEventType + location:windowPoint + modifierFlags:modifierFlags + timestamp:[[NSProcessInfo processInfo] systemUptime] + windowNumber:[[mView window] windowNumber] + context:nil + eventNumber:0 + clickCount:1 + pressure:0.0]; if (!event) return NS_ERROR_FAILURE; @@ -954,30 +970,35 @@ nsresult nsChildView::SynthesizeNativeMouseEvent(LayoutDeviceIntPoint aPoint, } nsresult nsChildView::SynthesizeNativeMouseScrollEvent( - mozilla::LayoutDeviceIntPoint aPoint, uint32_t aNativeMessage, double aDeltaX, double aDeltaY, - double aDeltaZ, uint32_t aModifierFlags, uint32_t aAdditionalFlags, nsIObserver* aObserver) { + mozilla::LayoutDeviceIntPoint aPoint, uint32_t aNativeMessage, + double aDeltaX, double aDeltaY, double aDeltaZ, uint32_t aModifierFlags, + uint32_t aAdditionalFlags, nsIObserver* aObserver) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; AutoObserverNotifier notifier(aObserver, "mousescrollevent"); - NSPoint pt = nsCocoaUtils::DevPixelsToCocoaPoints(aPoint, BackingScaleFactor()); + NSPoint pt = + nsCocoaUtils::DevPixelsToCocoaPoints(aPoint, BackingScaleFactor()); - // Move the mouse cursor to the requested position and reconnect it to the mouse. + // Move the mouse cursor to the requested position and reconnect it to the + // mouse. CGWarpMouseCursorPosition(NSPointToCGPoint(pt)); CGAssociateMouseAndMouseCursorPosition(true); // Mostly copied from http://stackoverflow.com/a/6130349 - CGScrollEventUnit units = (aAdditionalFlags & nsIDOMWindowUtils::MOUSESCROLL_SCROLL_LINES) - ? kCGScrollEventUnitLine - : kCGScrollEventUnitPixel; - CGEventRef cgEvent = CGEventCreateScrollWheelEvent(NULL, units, 3, (int32_t)aDeltaY, - (int32_t)aDeltaX, (int32_t)aDeltaZ); + CGScrollEventUnit units = + (aAdditionalFlags & nsIDOMWindowUtils::MOUSESCROLL_SCROLL_LINES) + ? kCGScrollEventUnitLine + : kCGScrollEventUnitPixel; + CGEventRef cgEvent = CGEventCreateScrollWheelEvent( + NULL, units, 3, (int32_t)aDeltaY, (int32_t)aDeltaX, (int32_t)aDeltaZ); if (!cgEvent) { return NS_ERROR_FAILURE; } if (aNativeMessage) { - CGEventSetIntegerValueField(cgEvent, kCGScrollWheelEventScrollPhase, aNativeMessage); + CGEventSetIntegerValueField(cgEvent, kCGScrollWheelEventScrollPhase, + aNativeMessage); } // On macOS 10.14 and up CGEventPost won't work because of changes in macOS @@ -992,7 +1013,8 @@ nsresult nsChildView::SynthesizeNativeMouseScrollEvent( CGEventSetLocation(cgEvent, location); uint64_t kNanosPerSec = 1000000000L; - CGEventSetTimestamp(cgEvent, [[NSProcessInfo processInfo] systemUptime] * kNanosPerSec); + CGEventSetTimestamp( + cgEvent, [[NSProcessInfo processInfo] systemUptime] * kNanosPerSec); NSEvent* event = [NSEvent eventWithCGEvent:cgEvent]; [event setValue:[mView window] forKey:@"_window"]; @@ -1005,8 +1027,9 @@ nsresult nsChildView::SynthesizeNativeMouseScrollEvent( } nsresult nsChildView::SynthesizeNativeTouchPoint( - uint32_t aPointerId, TouchPointerState aPointerState, mozilla::LayoutDeviceIntPoint aPoint, - double aPointerPressure, uint32_t aPointerOrientation, nsIObserver* aObserver) { + uint32_t aPointerId, TouchPointerState aPointerState, + mozilla::LayoutDeviceIntPoint aPoint, double aPointerPressure, + uint32_t aPointerOrientation, nsIObserver* aObserver) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; AutoObserverNotifier notifier(aObserver, "touchpoint"); @@ -1022,16 +1045,16 @@ nsresult nsChildView::SynthesizeNativeTouchPoint( LayoutDeviceIntPoint pointInWindow = aPoint - WidgetToScreenOffset(); MultiTouchInput inputToDispatch = UpdateSynthesizedTouchState( - mSynthesizedTouchInput.get(), TimeStamp::Now(), aPointerId, aPointerState, pointInWindow, - aPointerPressure, aPointerOrientation); + mSynthesizedTouchInput.get(), TimeStamp::Now(), aPointerId, aPointerState, + pointInWindow, aPointerPressure, aPointerOrientation); DispatchTouchInput(inputToDispatch); return NS_OK; NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -nsresult nsChildView::SynthesizeNativeTouchpadDoubleTap(mozilla::LayoutDeviceIntPoint aPoint, - uint32_t aModifierFlags) { +nsresult nsChildView::SynthesizeNativeTouchpadDoubleTap( + mozilla::LayoutDeviceIntPoint aPoint, uint32_t aModifierFlags) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; DispatchDoubleTapGesture(TimeStamp::Now(), aPoint - WidgetToScreenOffset(), @@ -1082,7 +1105,8 @@ void nsChildView::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent* aEvent) { // fullscreen. // 4. Ignore. // Case 1 and 2 are handled before we get here. Below, we handle case 3. - if (StaticPrefs::browser_fullscreen_exit_on_escape() && [cocoaEvent keyCode] == kVK_Escape && + if (StaticPrefs::browser_fullscreen_exit_on_escape() && + [cocoaEvent keyCode] == kVK_Escape && [[mView window] styleMask] & NSWindowStyleMaskFullScreen) { [[mView window] toggleFullScreen:nil]; } @@ -1102,10 +1126,11 @@ nsresult nsChildView::ActivateNativeMenuItemAt(const nsAString& indexString) { nsMenuUtilsX::CheckNativeMenuConsistency([NSApp mainMenu]); NSString* locationString = - [NSString stringWithCharacters:reinterpret_cast(indexString.BeginReading()) + [NSString stringWithCharacters:reinterpret_cast( + indexString.BeginReading()) length:indexString.Length()]; - NSMenuItem* item = - nsMenuUtilsX::NativeMenuItemWithLocation([NSApp mainMenu], locationString, true); + NSMenuItem* item = nsMenuUtilsX::NativeMenuItemWithLocation( + [NSApp mainMenu], locationString, true); // We can't perform an action on an item with a submenu, that will raise // an obj-c exception. if (item && ![item hasSubmenu]) { @@ -1192,8 +1217,9 @@ void nsChildView::Invalidate(const LayoutDeviceIntRect& aRect) { if (!mView || !mVisible) return; - NS_ASSERTION(GetWindowRenderer()->GetBackendType() != LayersBackend::LAYERS_WR, - "Shouldn't need to invalidate with accelerated OMTC layers!"); + NS_ASSERTION( + GetWindowRenderer()->GetBackendType() != LayersBackend::LAYERS_WR, + "Shouldn't need to invalidate with accelerated OMTC layers!"); EnsureContentLayerForMainThreadPainting(); mContentLayerInvalidRegion.OrWith(aRect.Intersect(GetBounds())); @@ -1232,7 +1258,8 @@ bool nsChildView::ShouldUseOffMainThreadCompositing() { #pragma mark - // Invokes callback and ProcessEvent methods on Event Listener object -nsresult nsChildView::DispatchEvent(WidgetGUIEvent* event, nsEventStatus& aStatus) { +nsresult nsChildView::DispatchEvent(WidgetGUIEvent* event, + nsEventStatus& aStatus) { RefPtr kungFuDeathGrip(this); #ifdef DEBUG @@ -1275,7 +1302,8 @@ nsresult nsChildView::DispatchEvent(WidgetGUIEvent* event, nsEventStatus& aStatu nsIWidget* nsChildView::GetWidgetForListenerEvents() { // If there is no listener, use the parent popup's listener if that exists. - if (!mWidgetListener && mParentWidget && mParentWidget->GetWindowType() == WindowType::Popup) { + if (!mWidgetListener && mParentWidget && + mParentWidget->GetWindowType() == WindowType::Popup) { return mParentWidget; } @@ -1330,8 +1358,8 @@ bool nsChildView::PaintWindowInDrawTarget(gfx::DrawTarget* aDT, nsAutoRetainCocoaObject kungFuDeathGrip(mView); if (GetWindowRenderer()->GetBackendType() == LayersBackend::LAYERS_NONE) { - nsBaseWidget::AutoLayerManagerSetup setupLayerManager(this, &targetContext, - BufferMode::BUFFER_NONE); + nsBaseWidget::AutoLayerManagerSetup setupLayerManager( + this, &targetContext, BufferMode::BUFFER_NONE); return PaintWindow(aRegion); } return false; @@ -1349,7 +1377,8 @@ void nsChildView::EnsureContentLayerForMainThreadPainting() { } if (!mContentLayer) { mPoolHandle = SurfacePool::Create(0)->GetHandleForGL(nullptr); - RefPtr contentLayer = mNativeLayerRoot->CreateLayer(size, false, mPoolHandle); + RefPtr contentLayer = + mNativeLayerRoot->CreateLayer(size, false, mPoolHandle); mNativeLayerRoot->AppendLayer(contentLayer); mContentLayer = contentLayer->AsNativeLayerCA(); mContentLayer->SetSurfaceIsFlipped(false); @@ -1361,8 +1390,8 @@ void nsChildView::PaintWindowInContentLayer() { EnsureContentLayerForMainThreadPainting(); mPoolHandle->OnBeginFrame(); RefPtr dt = mContentLayer->NextSurfaceAsDrawTarget( - gfx::IntRect({}, mContentLayer->GetSize()), mContentLayerInvalidRegion.ToUnknownRegion(), - gfx::BackendType::SKIA); + gfx::IntRect({}, mContentLayer->GetSize()), + mContentLayerInvalidRegion.ToUnknownRegion(), gfx::BackendType::SKIA); if (!dt) { return; } @@ -1389,10 +1418,11 @@ void nsChildView::HandleMainThreadCATransaction() { } { - // Apply the changes inside mNativeLayerRoot to the underlying CALayers. Now is a - // good time to call this because we know we're currently inside a main thread - // CATransaction, and the lock makes sure that no composition is currently in - // progress, so we won't present half-composited state to the screen. + // Apply the changes inside mNativeLayerRoot to the underlying CALayers. Now + // is a good time to call this because we know we're currently inside a main + // thread CATransaction, and the lock makes sure that no composition is + // currently in progress, so we won't present half-composited state to the + // screen. MutexAutoLock lock(mCompositingLock); mNativeLayerRoot->CommitToScreen(); } @@ -1405,7 +1435,8 @@ void nsChildView::HandleMainThreadCATransaction() { void nsChildView::ReportMoveEvent() { NotifyWindowMoved(mBounds.x, mBounds.y); } void nsChildView::ReportSizeEvent() { - if (mWidgetListener) mWidgetListener->WindowResized(this, mBounds.width, mBounds.height); + if (mWidgetListener) + mWidgetListener->WindowResized(this, mBounds.width, mBounds.height); } #pragma mark - @@ -1431,10 +1462,12 @@ LayoutDeviceIntPoint nsChildView::WidgetToScreenOffset() { // The returned point is in bottom-left coordinates. origin = [mView convertPoint:origin toView:nil]; - // 2. We turn the window-coord rect's origin into screen (still bottom-left) coords. + // 2. We turn the window-coord rect's origin into screen (still bottom-left) + // coords. origin = nsCocoaUtils::ConvertPointToScreen([mView window], origin); - // 3. Since we're dealing in bottom-left coords, we need to make it top-left coords + // 3. Since we're dealing in bottom-left coords, we need to make it top-left + // coords // before we pass it back to Gecko. FlipCocoaScreenCoordinate(origin); @@ -1468,17 +1501,25 @@ uint32_t nsChildView::GetCurrentInputEventCount() { // Can't use kCGAnyInputEventType because that updates too rarely for us (and // always in increments of 30+!) and because apparently it's sort of broken // on Tiger. So just go ahead and query the counters we care about. - static const CGEventType eventTypes[] = { - kCGEventLeftMouseDown, kCGEventLeftMouseUp, kCGEventRightMouseDown, - kCGEventRightMouseUp, kCGEventMouseMoved, kCGEventLeftMouseDragged, - kCGEventRightMouseDragged, kCGEventKeyDown, kCGEventKeyUp, - kCGEventScrollWheel, kCGEventTabletPointer, kCGEventOtherMouseDown, - kCGEventOtherMouseUp, kCGEventOtherMouseDragged}; + static const CGEventType eventTypes[] = {kCGEventLeftMouseDown, + kCGEventLeftMouseUp, + kCGEventRightMouseDown, + kCGEventRightMouseUp, + kCGEventMouseMoved, + kCGEventLeftMouseDragged, + kCGEventRightMouseDragged, + kCGEventKeyDown, + kCGEventKeyUp, + kCGEventScrollWheel, + kCGEventTabletPointer, + kCGEventOtherMouseDown, + kCGEventOtherMouseUp, + kCGEventOtherMouseDragged}; uint32_t eventCount = 0; for (uint32_t i = 0; i < ArrayLength(eventTypes); ++i) { - eventCount += - CGEventSourceCounterForEventType(kCGEventSourceStateCombinedSessionState, eventTypes[i]); + eventCount += CGEventSourceCounterForEventType( + kCGEventSourceStateCombinedSessionState, eventTypes[i]); } return eventCount; } @@ -1492,7 +1533,8 @@ bool nsChildView::HasPendingInputEvent() { return DoHasPendingInputEvent(); } #pragma mark - -void nsChildView::SetInputContext(const InputContext& aContext, const InputContextAction& aAction) { +void nsChildView::SetInputContext(const InputContext& aContext, + const InputContextAction& aAction) { NS_ENSURE_TRUE_VOID(mTextInputHandler); if (mTextInputHandler->IsFocused()) { @@ -1513,7 +1555,8 @@ void nsChildView::SetInputContext(const InputContext& aContext, const InputConte mTextInputHandler->SetASCIICapableOnly(false); mTextInputHandler->EnableIME(true); if (mInputContext.mIMEState.mOpen != IMEState::DONT_CHANGE_OPEN_STATE) { - mTextInputHandler->SetIMEOpenState(mInputContext.mIMEState.mOpen == IMEState::OPEN); + mTextInputHandler->SetIMEOpenState(mInputContext.mIMEState.mOpen == + IMEState::OPEN); } break; case IMEEnabled::Disabled: @@ -1533,8 +1576,9 @@ InputContext nsChildView::GetInputContext() { switch (mInputContext.mIMEState.mEnabled) { case IMEEnabled::Enabled: if (mTextInputHandler) { - mInputContext.mIMEState.mOpen = - mTextInputHandler->IsIMEOpened() ? IMEState::OPEN : IMEState::CLOSED; + mInputContext.mIMEState.mOpen = mTextInputHandler->IsIMEOpened() + ? IMEState::OPEN + : IMEState::CLOSED; break; } // If mTextInputHandler is null, set CLOSED instead... @@ -1546,19 +1590,22 @@ InputContext nsChildView::GetInputContext() { return mInputContext; } -TextEventDispatcherListener* nsChildView::GetNativeTextEventDispatcherListener() { +TextEventDispatcherListener* +nsChildView::GetNativeTextEventDispatcherListener() { if (NS_WARN_IF(!mTextInputHandler)) { return nullptr; } return mTextInputHandler; } -nsresult nsChildView::AttachNativeKeyEvent(mozilla::WidgetKeyboardEvent& aEvent) { +nsresult nsChildView::AttachNativeKeyEvent( + mozilla::WidgetKeyboardEvent& aEvent) { NS_ENSURE_TRUE(mTextInputHandler, NS_ERROR_NOT_AVAILABLE); return mTextInputHandler->AttachNativeKeyEvent(aEvent); } -bool nsChildView::GetEditCommands(NativeKeyBindingsType aType, const WidgetKeyboardEvent& aEvent, +bool nsChildView::GetEditCommands(NativeKeyBindingsType aType, + const WidgetKeyboardEvent& aEvent, nsTArray& aCommands) { // Validate the arguments. if (NS_WARN_IF(!nsIWidget::GetEditCommands(aType, aEvent, aCommands))) { @@ -1589,9 +1636,11 @@ NSView* nsChildView::GetEditorView() { // need any layout information right now. queryContentState.mNeedsToFlushLayout = false; DispatchWindowEvent(queryContentState); - if (queryContentState.Succeeded() && queryContentState.mReply->mFocusedWidget) { + if (queryContentState.Succeeded() && + queryContentState.mReply->mFocusedWidget) { NSView* view = static_cast*>( - queryContentState.mReply->mFocusedWidget->GetNativeData(NS_NATIVE_WIDGET)); + queryContentState.mReply->mFocusedWidget->GetNativeData( + NS_NATIVE_WIDGET)); if (view) editorView = view; } return editorView; @@ -1606,11 +1655,16 @@ void nsChildView::CreateCompositor() { } } -void nsChildView::ConfigureAPZCTreeManager() { nsBaseWidget::ConfigureAPZCTreeManager(); } +void nsChildView::ConfigureAPZCTreeManager() { + nsBaseWidget::ConfigureAPZCTreeManager(); +} -void nsChildView::ConfigureAPZControllerThread() { nsBaseWidget::ConfigureAPZControllerThread(); } +void nsChildView::ConfigureAPZControllerThread() { + nsBaseWidget::ConfigureAPZControllerThread(); +} -bool nsChildView::PreRender(WidgetRenderingContext* aContext) MOZ_NO_THREAD_SAFETY_ANALYSIS { +bool nsChildView::PreRender(WidgetRenderingContext* aContext) + MOZ_NO_THREAD_SAFETY_ANALYSIS { // The lock makes sure that we don't attempt to tear down the view while // compositing. That would make us unable to call postRender on it when the // composition is done, thus keeping the GL context locked forever. @@ -1623,14 +1677,18 @@ bool nsChildView::PreRender(WidgetRenderingContext* aContext) MOZ_NO_THREAD_SAFE return true; } -void nsChildView::PostRender(WidgetRenderingContext* aContext) MOZ_NO_THREAD_SAFETY_ANALYSIS { +void nsChildView::PostRender(WidgetRenderingContext* aContext) + MOZ_NO_THREAD_SAFETY_ANALYSIS { mCompositingLock.Unlock(); } -RefPtr nsChildView::GetNativeLayerRoot() { return mNativeLayerRoot; } +RefPtr nsChildView::GetNativeLayerRoot() { + return mNativeLayerRoot; +} -static int32_t FindTitlebarBottom(const nsTArray& aThemeGeometries, - int32_t aWindowWidth) { +static int32_t FindTitlebarBottom( + const nsTArray& aThemeGeometries, + int32_t aWindowWidth) { int32_t titlebarBottom = 0; for (auto& g : aThemeGeometries) { if (g.mType == eThemeGeometryTypeTitlebar && g.mRect.X() <= 0 && @@ -1641,8 +1699,9 @@ static int32_t FindTitlebarBottom(const nsTArray& aThe return titlebarBottom; } -static int32_t FindUnifiedToolbarBottom(const nsTArray& aThemeGeometries, - int32_t aWindowWidth, int32_t aTitlebarBottom) { +static int32_t FindUnifiedToolbarBottom( + const nsTArray& aThemeGeometries, + int32_t aWindowWidth, int32_t aTitlebarBottom) { int32_t unifiedToolbarBottom = aTitlebarBottom; for (uint32_t i = 0; i < aThemeGeometries.Length(); ++i) { const nsIWidget::ThemeGeometry& g = aThemeGeometries[i]; @@ -1666,7 +1725,8 @@ static LayoutDeviceIntRect FindFirstRectOfType( return LayoutDeviceIntRect(); } -void nsChildView::UpdateThemeGeometries(const nsTArray& aThemeGeometries) { +void nsChildView::UpdateThemeGeometries( + const nsTArray& aThemeGeometries) { if (![mView window]) return; UpdateVibrancy(aThemeGeometries); @@ -1678,23 +1738,28 @@ void nsChildView::UpdateThemeGeometries(const nsTArray& aThemeGeo int32_t titlebarBottom = FindTitlebarBottom(aThemeGeometries, windowWidth); int32_t unifiedToolbarBottom = FindUnifiedToolbarBottom(aThemeGeometries, windowWidth, titlebarBottom); - int32_t toolboxBottom = FindFirstRectOfType(aThemeGeometries, eThemeGeometryTypeToolbox).YMost(); + int32_t toolboxBottom = + FindFirstRectOfType(aThemeGeometries, eThemeGeometryTypeToolbox).YMost(); ToolbarWindow* win = (ToolbarWindow*)[mView window]; - int32_t titlebarHeight = - [win drawsContentsIntoWindowFrame] ? 0 : CocoaPointsToDevPixels([win titlebarHeight]); + int32_t titlebarHeight = [win drawsContentsIntoWindowFrame] + ? 0 + : CocoaPointsToDevPixels([win titlebarHeight]); int32_t devUnifiedHeight = titlebarHeight + unifiedToolbarBottom; [win setUnifiedToolbarHeight:DevPixelsToCocoaPoints(devUnifiedHeight)]; int32_t sheetPositionDevPx = std::max(toolboxBottom, unifiedToolbarBottom); NSPoint sheetPositionView = {0, DevPixelsToCocoaPoints(sheetPositionDevPx)}; - NSPoint sheetPositionWindow = [mView convertPoint:sheetPositionView toView:nil]; + NSPoint sheetPositionWindow = [mView convertPoint:sheetPositionView + toView:nil]; [win setSheetAttachmentPosition:sheetPositionWindow.y]; // Update titlebar control offsets. LayoutDeviceIntRect windowButtonRect = FindFirstRectOfType(aThemeGeometries, eThemeGeometryTypeWindowButtons); - [win placeWindowButtons:[mView convertRect:DevPixelsToCocoaPoints(windowButtonRect) toView:nil]]; + [win placeWindowButtons:[mView convertRect:DevPixelsToCocoaPoints( + windowButtonRect) + toView:nil]]; } static Maybe ThemeGeometryTypeToVibrancyType( @@ -1718,10 +1783,12 @@ static Maybe ThemeGeometryTypeToVibrancyType( } static LayoutDeviceIntRegion GatherVibrantRegion( - const nsTArray& aThemeGeometries, VibrancyType aVibrancyType) { + const nsTArray& aThemeGeometries, + VibrancyType aVibrancyType) { LayoutDeviceIntRegion region; for (auto& geometry : aThemeGeometries) { - if (ThemeGeometryTypeToVibrancyType(geometry.mType) == Some(aVibrancyType)) { + if (ThemeGeometryTypeToVibrancyType(geometry.mType) == + Some(aVibrancyType)) { region.OrWith(geometry.mRect); } } @@ -1732,7 +1799,8 @@ template static void MakeRegionsNonOverlappingImpl(Region& aOutUnion) {} template -static void MakeRegionsNonOverlappingImpl(Region& aOutUnion, Region& aFirst, Regions&... aRest) { +static void MakeRegionsNonOverlappingImpl(Region& aOutUnion, Region& aFirst, + Regions&... aRest) { MakeRegionsNonOverlappingImpl(aOutUnion, aRest...); aFirst.SubOut(aOutUnion); aOutUnion.OrWith(aFirst); @@ -1748,29 +1816,35 @@ static void MakeRegionsNonOverlapping(Region& aFirst, Regions&... aRest) { MakeRegionsNonOverlappingImpl(unionOfAll, aFirst, aRest...); } -void nsChildView::UpdateVibrancy(const nsTArray& aThemeGeometries) { - LayoutDeviceIntRegion menuRegion = GatherVibrantRegion(aThemeGeometries, VibrancyType::MENU); +void nsChildView::UpdateVibrancy( + const nsTArray& aThemeGeometries) { + LayoutDeviceIntRegion menuRegion = + GatherVibrantRegion(aThemeGeometries, VibrancyType::MENU); LayoutDeviceIntRegion tooltipRegion = GatherVibrantRegion(aThemeGeometries, VibrancyType::TOOLTIP); LayoutDeviceIntRegion highlightedMenuItemRegion = GatherVibrantRegion(aThemeGeometries, VibrancyType::HIGHLIGHTED_MENUITEM); LayoutDeviceIntRegion sourceListRegion = GatherVibrantRegion(aThemeGeometries, VibrancyType::SOURCE_LIST); - LayoutDeviceIntRegion sourceListSelectionRegion = - GatherVibrantRegion(aThemeGeometries, VibrancyType::SOURCE_LIST_SELECTION); - LayoutDeviceIntRegion activeSourceListSelectionRegion = - GatherVibrantRegion(aThemeGeometries, VibrancyType::ACTIVE_SOURCE_LIST_SELECTION); + LayoutDeviceIntRegion sourceListSelectionRegion = GatherVibrantRegion( + aThemeGeometries, VibrancyType::SOURCE_LIST_SELECTION); + LayoutDeviceIntRegion activeSourceListSelectionRegion = GatherVibrantRegion( + aThemeGeometries, VibrancyType::ACTIVE_SOURCE_LIST_SELECTION); - MakeRegionsNonOverlapping(menuRegion, tooltipRegion, highlightedMenuItemRegion, sourceListRegion, - sourceListSelectionRegion, activeSourceListSelectionRegion); + MakeRegionsNonOverlapping( + menuRegion, tooltipRegion, highlightedMenuItemRegion, sourceListRegion, + sourceListSelectionRegion, activeSourceListSelectionRegion); auto& vm = EnsureVibrancyManager(); bool changed = false; changed |= vm.UpdateVibrantRegion(VibrancyType::MENU, menuRegion); changed |= vm.UpdateVibrantRegion(VibrancyType::TOOLTIP, tooltipRegion); - changed |= vm.UpdateVibrantRegion(VibrancyType::HIGHLIGHTED_MENUITEM, highlightedMenuItemRegion); - changed |= vm.UpdateVibrantRegion(VibrancyType::SOURCE_LIST, sourceListRegion); - changed |= vm.UpdateVibrantRegion(VibrancyType::SOURCE_LIST_SELECTION, sourceListSelectionRegion); + changed |= vm.UpdateVibrantRegion(VibrancyType::HIGHLIGHTED_MENUITEM, + highlightedMenuItemRegion); + changed |= + vm.UpdateVibrantRegion(VibrancyType::SOURCE_LIST, sourceListRegion); + changed |= vm.UpdateVibrantRegion(VibrancyType::SOURCE_LIST_SELECTION, + sourceListSelectionRegion); changed |= vm.UpdateVibrantRegion(VibrancyType::ACTIVE_SOURCE_LIST_SELECTION, activeSourceListSelectionRegion); @@ -1782,7 +1856,8 @@ void nsChildView::UpdateVibrancy(const nsTArray& aThemeGeometries mozilla::VibrancyManager& nsChildView::EnsureVibrancyManager() { MOZ_ASSERT(mView, "Only call this once we have a view!"); if (!mVibrancyManager) { - mVibrancyManager = MakeUnique(*this, [mView vibrancyViewsContainer]); + mVibrancyManager = + MakeUnique(*this, [mView vibrancyViewsContainer]); } return *mVibrancyManager; } @@ -1826,14 +1901,16 @@ void nsChildView::UpdateBoundsFromView() { } @end -void nsChildView::UpdateWindowDraggingRegion(const LayoutDeviceIntRegion& aRegion) { +void nsChildView::UpdateWindowDraggingRegion( + const LayoutDeviceIntRegion& aRegion) { // mView returns YES from mouseDownCanMoveWindow, so we need to put NSViews // that return NO from mouseDownCanMoveWindow in the places that shouldn't // be draggable. We can't do it the other way round because returning // YES from mouseDownCanMoveWindow doesn't have any effect if there's a // superview that returns NO. LayoutDeviceIntRegion nonDraggable; - nonDraggable.Sub(LayoutDeviceIntRect(0, 0, mBounds.width, mBounds.height), aRegion); + nonDraggable.Sub(LayoutDeviceIntRect(0, 0, mBounds.width, mBounds.height), + aRegion); __block bool changed = false; @@ -1886,7 +1963,8 @@ void nsChildView::DispatchAPZWheelInputEvent(InputData& aEvent) { // Give the swipe tracker a first pass at the event. If a new pan gesture // has been started since the beginning of the swipe, the swipe tracker // will know to ignore the event. - nsEventStatus status = mSwipeTracker->ProcessEvent(aEvent.AsPanGestureInput()); + nsEventStatus status = + mSwipeTracker->ProcessEvent(aEvent.AsPanGestureInput()); if (status == nsEventStatus_eConsumeNoDefault) { return; } @@ -1924,7 +2002,8 @@ void nsChildView::DispatchAPZWheelInputEvent(InputData& aEvent) { MOZ_CRASH("unsupported event type"); return; } - if (event.mMessage == eWheel && (event.mDeltaX != 0 || event.mDeltaY != 0)) { + if (event.mMessage == eWheel && + (event.mDeltaX != 0 || event.mDeltaY != 0)) { ProcessUntransformedAPZEvent(&event, result); } return; @@ -1958,8 +2037,9 @@ void nsChildView::DispatchDoubleTapGesture(TimeStamp aEventTimeStamp, if (StaticPrefs::apz_mac_enable_double_tap_zoom_touchpad_gesture()) { TapGestureInput event{ TapGestureInput::TAPGESTURE_DOUBLE, aEventTimeStamp, - ViewAs(aScreenPosition, - PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent), + ViewAs( + aScreenPosition, + PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent), aModifiers}; DispatchAPZInputEvent(event); @@ -1977,14 +2057,16 @@ void nsChildView::DispatchDoubleTapGesture(TimeStamp aEventTimeStamp, } } -void nsChildView::LookUpDictionary(const nsAString& aText, - const nsTArray& aFontRangeArray, - const bool aIsVertical, const LayoutDeviceIntPoint& aPoint) { +void nsChildView::LookUpDictionary( + const nsAString& aText, const nsTArray& aFontRangeArray, + const bool aIsVertical, const LayoutDeviceIntPoint& aPoint) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - NSMutableAttributedString* attrStr = nsCocoaUtils::GetNSMutableAttributedString( - aText, aFontRangeArray, aIsVertical, BackingScaleFactor()); - NSPoint pt = nsCocoaUtils::DevPixelsToCocoaPoints(aPoint, BackingScaleFactor()); + NSMutableAttributedString* attrStr = + nsCocoaUtils::GetNSMutableAttributedString( + aText, aFontRangeArray, aIsVertical, BackingScaleFactor()); + NSPoint pt = + nsCocoaUtils::DevPixelsToCocoaPoints(aPoint, BackingScaleFactor()); NSDictionary* attributes = [attrStr attributesAtIndex:0 effectiveRange:nil]; NSFont* font = [attributes objectForKey:NSFontAttributeName]; if (font) { @@ -2008,7 +2090,8 @@ already_AddRefed nsChildView::GetDocumentAccessible() { // now being enabled again. if (mAccessible && mAccessible->IsAlive()) { RefPtr ret; - CallQueryReferent(mAccessible.get(), static_cast(getter_AddRefs(ret))); + CallQueryReferent(mAccessible.get(), static_cast( + getter_AddRefs(ret))); return ret.forget(); } @@ -2024,7 +2107,8 @@ already_AddRefed nsChildView::GetDocumentAccessible() { class WidgetsReleaserRunnable final : public mozilla::Runnable { public: explicit WidgetsReleaserRunnable(nsTArray>&& aWidgetArray) - : mozilla::Runnable("WidgetsReleaserRunnable"), mWidgetArray(std::move(aWidgetArray)) {} + : mozilla::Runnable("WidgetsReleaserRunnable"), + mWidgetArray(std::move(aWidgetArray)) {} // Do nothing; all this runnable does is hold a reference the widgets in // mWidgetArray, and those references will be dropped when this runnable @@ -2062,16 +2146,16 @@ class WidgetsReleaserRunnable final : public mozilla::Runnable { @implementation ChildView -// globalDragPboard is non-null during native drag sessions that did not originate -// in our native NSView (it is set in |draggingEntered:|). It is unset when the -// drag session ends for this view, either with the mouse exiting or when a drop -// occurs in this view. +// globalDragPboard is non-null during native drag sessions that did not +// originate in our native NSView (it is set in |draggingEntered:|). It is unset +// when the drag session ends for this view, either with the mouse exiting or +// when a drop occurs in this view. NSPasteboard* globalDragPboard = nil; // gLastDragView and gLastDragMouseDownEvent are used to communicate information -// to the drag service during drag invocation (starting a drag in from the view). -// gLastDragView is only non-null while a mouse button is pressed, so between -// mouseDown and mouseUp. +// to the drag service during drag invocation (starting a drag in from the +// view). gLastDragView is only non-null while a mouse button is pressed, so +// between mouseDown and mouseUp. NSView* gLastDragView = nil; // [weak] NSEvent* gLastDragMouseDownEvent = nil; // [strong] @@ -2094,16 +2178,19 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] [aView registerForDraggedTypes: [NSArray - arrayWithObjects:[UTIHelper stringFromPboardType:NSFilenamesPboardType], - [UTIHelper stringFromPboardType:kMozFileUrlsPboardType], - [UTIHelper stringFromPboardType:NSPasteboardTypeString], - [UTIHelper stringFromPboardType:NSPasteboardTypeHTML], - [UTIHelper - stringFromPboardType:(NSString*)kPasteboardTypeFileURLPromise], - [UTIHelper stringFromPboardType:kMozWildcardPboardType], - [UTIHelper stringFromPboardType:kPublicUrlPboardType], - [UTIHelper stringFromPboardType:kPublicUrlNamePboardType], - [UTIHelper stringFromPboardType:kUrlsWithTitlesPboardType], nil]]; + arrayWithObjects: + [UTIHelper stringFromPboardType:NSFilenamesPboardType], + [UTIHelper stringFromPboardType:kMozFileUrlsPboardType], + [UTIHelper stringFromPboardType:NSPasteboardTypeString], + [UTIHelper stringFromPboardType:NSPasteboardTypeHTML], + [UTIHelper + stringFromPboardType:(NSString*) + kPasteboardTypeFileURLPromise], + [UTIHelper stringFromPboardType:kMozWildcardPboardType], + [UTIHelper stringFromPboardType:kPublicUrlPboardType], + [UTIHelper stringFromPboardType:kPublicUrlNamePboardType], + [UTIHelper stringFromPboardType:kUrlsWithTitlesPboardType], + nil]]; } // initWithFrame:geckoChild: @@ -2131,17 +2218,22 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] mCancelSwipeAnimation = nil; #endif - mNonDraggableViewsContainer = [[ViewRegionContainerView alloc] initWithFrame:[self bounds]]; - mVibrancyViewsContainer = [[ViewRegionContainerView alloc] initWithFrame:[self bounds]]; + mNonDraggableViewsContainer = + [[ViewRegionContainerView alloc] initWithFrame:[self bounds]]; + mVibrancyViewsContainer = + [[ViewRegionContainerView alloc] initWithFrame:[self bounds]]; - [mNonDraggableViewsContainer setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; - [mVibrancyViewsContainer setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; + [mNonDraggableViewsContainer + setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; + [mVibrancyViewsContainer + setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [self addSubview:mNonDraggableViewsContainer]; [self addSubview:mVibrancyViewsContainer]; mPixelHostingView = [[PixelHostingView alloc] initWithFrame:[self bounds]]; - [mPixelHostingView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; + [mPixelHostingView + setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [self addSubview:mPixelHostingView]; @@ -2233,7 +2325,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] NS_IF_RELEASE(mDragService); } -// mozView method, return our gecko child view widget. Note this does not AddRef. +// mozView method, return our gecko child view widget. Note this does not +// AddRef. - (nsIWidget*)widget { return static_cast(mGeckoChild); } @@ -2241,7 +2334,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] - (NSString*)description { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - return [NSString stringWithFormat:@"ChildView %p, gecko child %p, frame %@", self, mGeckoChild, + return [NSString stringWithFormat:@"ChildView %p, gecko child %p, frame %@", + self, mGeckoChild, NSStringFromRect([self frame])]; NS_OBJC_END_TRY_BLOCK_RETURN(nil); @@ -2253,8 +2347,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] return YES; } -// We accept key and mouse events, so don't keep passing them up the chain. Allow -// this to be a 'focused' widget for event dispatch. +// We accept key and mouse events, so don't keep passing them up the chain. +// Allow this to be a 'focused' widget for event dispatch. - (BOOL)acceptsFirstResponder { return YES; } @@ -2297,7 +2391,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] } - (void)viewWillStartLiveResize { - nsCocoaWindow* windowWidget = mGeckoChild ? mGeckoChild->GetAppWindowWidget() : nullptr; + nsCocoaWindow* windowWidget = + mGeckoChild ? mGeckoChild->GetAppWindowWidget() : nullptr; if (windowWidget) { windowWidget->NotifyLiveResizeStarted(); } @@ -2310,7 +2405,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] // is null here, that might be problematic because we might get stuck with // a content process that has the displayport suppressed. If that scenario // arises (I'm not sure that it does) we will need to handle it gracefully. - nsCocoaWindow* windowWidget = mGeckoChild ? mGeckoChild->GetAppWindowWidget() : nullptr; + nsCocoaWindow* windowWidget = + mGeckoChild ? mGeckoChild->GetAppWindowWidget() : nullptr; if (windowWidget) { windowWidget->NotifyLiveResizeStopped(); } @@ -2390,10 +2486,11 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] if (!isWheelTypeEvent && rollupListener->RollupNativeMenu()) { // A native menu was rolled up. - // Don't consume this event; if the menu wanted to consume this event it would already have done - // so and we wouldn't even get here. For example, we won't get here for left clicks that close - // native menus (because the native menu consumes it), but we will get here for right clicks - // that close native menus, and we do not want to consume those right clicks. + // Don't consume this event; if the menu wanted to consume this event it + // would already have done so and we wouldn't even get here. For example, we + // won't get here for left clicks that close native menus (because the + // native menu consumes it), but we will get here for right clicks that + // close native menus, and we do not want to consume those right clicks. return NO; } @@ -2402,7 +2499,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] return consumeEvent; } - NSWindow* currentPopup = static_cast(rollupWidget->GetNativeData(NS_NATIVE_WINDOW)); + NSWindow* currentPopup = + static_cast(rollupWidget->GetNativeData(NS_NATIVE_WINDOW)); if (nsCocoaUtils::IsEventOverWindow(theEvent, currentPopup)) { return consumeEvent; } @@ -2440,8 +2538,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] } LayoutDeviceIntPoint devPoint; - nsIRollupListener::RollupOptions rollupOptions{popupsToRollup, - nsIRollupListener::FlushViews::Yes}; + nsIRollupListener::RollupOptions rollupOptions{ + popupsToRollup, nsIRollupListener::FlushViews::Yes}; if ([theEvent type] == NSEventTypeLeftMouseDown) { NSPoint point = [NSEvent mouseLocation]; FlipCocoaScreenCoordinate(point); @@ -2507,21 +2605,24 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] // we can do by checking and setting mGestureState appropriately. A secondary // result of that function is to send the final eMagnifyGesture event when // the gesture ends, but APZ takes care of that for us. - if (mGestureState == eGestureState_RotateGesture && [anEvent phase] != NSEventPhaseBegan) { + if (mGestureState == eGestureState_RotateGesture && + [anEvent phase] != NSEventPhaseBegan) { // If we're already in a rotation and not "starting" a magnify, abort. return; } mGestureState = eGestureState_MagnifyGesture; - NSPoint locationInWindow = nsCocoaUtils::EventLocationForWindow(anEvent, [self window]); - ScreenPoint position = - ViewAs([self convertWindowCoordinatesRoundDown:locationInWindow], - PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent); - ExternalPoint screenOffset = - ViewAs(mGeckoChild->WidgetToScreenOffset(), - PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent); + NSPoint locationInWindow = + nsCocoaUtils::EventLocationForWindow(anEvent, [self window]); + ScreenPoint position = ViewAs( + [self convertWindowCoordinatesRoundDown:locationInWindow], + PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent); + ExternalPoint screenOffset = ViewAs( + mGeckoChild->WidgetToScreenOffset(), + PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent); - TimeStamp eventTimeStamp = nsCocoaUtils::GetEventTimeStamp([anEvent timestamp]); + TimeStamp eventTimeStamp = + nsCocoaUtils::GetEventTimeStamp([anEvent timestamp]); NSEventPhase eventPhase = [anEvent phase]; PinchGestureInput::PinchGestureType pinchGestureType; @@ -2563,7 +2664,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] - (void)smartMagnifyWithEvent:(NSEvent*)anEvent { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - if (!anEvent || !mGeckoChild || [self beginOrEndGestureForEventPhase:anEvent]) { + if (!anEvent || !mGeckoChild || + [self beginOrEndGestureForEventPhase:anEvent]) { return; } @@ -2574,12 +2676,16 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] nsAutoRetainCocoaObject kungFuDeathGrip(self); if (StaticPrefs::apz_mac_enable_double_tap_zoom_touchpad_gesture()) { - TimeStamp eventTimeStamp = nsCocoaUtils::GetEventTimeStamp([anEvent timestamp]); - NSPoint locationInWindow = nsCocoaUtils::EventLocationForWindow(anEvent, [self window]); - LayoutDevicePoint position = [self convertWindowCoordinatesRoundDown:locationInWindow]; + TimeStamp eventTimeStamp = + nsCocoaUtils::GetEventTimeStamp([anEvent timestamp]); + NSPoint locationInWindow = + nsCocoaUtils::EventLocationForWindow(anEvent, [self window]); + LayoutDevicePoint position = + [self convertWindowCoordinatesRoundDown:locationInWindow]; - mGeckoChild->DispatchDoubleTapGesture(eventTimeStamp, RoundedToInt(position), - nsCocoaUtils::ModifiersForEvent(anEvent)); + mGeckoChild->DispatchDoubleTapGesture( + eventTimeStamp, RoundedToInt(position), + nsCocoaUtils::ModifiersForEvent(anEvent)); } else { // Setup the "double tap" event. WidgetSimpleGestureEvent geckoEvent(true, eTapGesture, mGeckoChild); @@ -2599,7 +2705,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] - (void)rotateWithEvent:(NSEvent*)anEvent { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - if (!anEvent || !mGeckoChild || [self beginOrEndGestureForEventPhase:anEvent]) { + if (!anEvent || !mGeckoChild || + [self beginOrEndGestureForEventPhase:anEvent]) { return; } @@ -2629,7 +2736,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] [self convertCocoaMouseEvent:anEvent toGeckoEvent:&geckoEvent]; geckoEvent.mDelta = -rotation; if (rotation > 0.0) { - geckoEvent.mDirection = dom::SimpleGestureEvent_Binding::ROTATION_COUNTERCLOCKWISE; + geckoEvent.mDirection = + dom::SimpleGestureEvent_Binding::ROTATION_COUNTERCLOCKWISE; } else { geckoEvent.mDirection = dom::SimpleGestureEvent_Binding::ROTATION_CLOCKWISE; } @@ -2658,7 +2766,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] return true; } - if (aEvent.phase == NSEventPhaseEnded || aEvent.phase == NSEventPhaseCancelled) { + if (aEvent.phase == NSEventPhaseEnded || + aEvent.phase == NSEventPhaseCancelled) { [self endGestureWithEvent:aEvent]; return true; } @@ -2694,9 +2803,11 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] [self convertCocoaMouseEvent:anEvent toGeckoEvent:&geckoEvent]; geckoEvent.mDelta = -mCumulativeRotation; if (mCumulativeRotation > 0.0) { - geckoEvent.mDirection = dom::SimpleGestureEvent_Binding::ROTATION_COUNTERCLOCKWISE; + geckoEvent.mDirection = + dom::SimpleGestureEvent_Binding::ROTATION_COUNTERCLOCKWISE; } else { - geckoEvent.mDirection = dom::SimpleGestureEvent_Binding::ROTATION_CLOCKWISE; + geckoEvent.mDirection = + dom::SimpleGestureEvent_Binding::ROTATION_CLOCKWISE; } // Send the event. @@ -2766,7 +2877,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] nsAutoRetainCocoaObject kungFuDeathGrip(self); if ([self maybeRollup:theEvent] || - !ChildViewMouseTracker::WindowAcceptsEvent([self window], theEvent, self, isClickThrough)) { + !ChildViewMouseTracker::WindowAcceptsEvent([self window], theEvent, self, + isClickThrough)) { // Remember blocking because that means we want to block mouseup as well. mBlockedLastMouseDown = YES; return; @@ -2778,7 +2890,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] return; } - WidgetMouseEvent geckoEvent(true, eMouseDown, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eMouseDown, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent]; NSInteger clickCount = [theEvent clickCount]; @@ -2824,7 +2937,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] nsAutoRetainCocoaObject kungFuDeathGrip(self); - WidgetMouseEvent geckoEvent(true, eMouseUp, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eMouseUp, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent]; if (!StaticPrefs::dom_event_treat_ctrl_click_as_right_click_disabled() && @@ -2839,8 +2953,9 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] LayoutDeviceIntPoint pos = geckoEvent.mRefPoint; // This might destroy our widget (and null out mGeckoChild). - bool defaultPrevented = (mGeckoChild->DispatchInputEvent(&geckoEvent).mContentStatus == - nsEventStatus_eConsumeNoDefault); + bool defaultPrevented = + (mGeckoChild->DispatchInputEvent(&geckoEvent).mContentStatus == + nsEventStatus_eConsumeNoDefault); if (!mGeckoChild) { return; @@ -2864,8 +2979,10 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] exitFrom:(WidgetMouseEvent::ExitFrom)aExitFrom { if (!mGeckoChild) return; - NSPoint windowEventLocation = nsCocoaUtils::EventLocationForWindow(aEvent, [self window]); - NSPoint localEventLocation = [self convertPoint:windowEventLocation fromView:nil]; + NSPoint windowEventLocation = + nsCocoaUtils::EventLocationForWindow(aEvent, [self window]); + NSPoint localEventLocation = [self convertPoint:windowEventLocation + fromView:nil]; EventMessage msg = aEnter ? eMouseEnterIntoWidget : eMouseExitFromWidget; WidgetMouseEvent event(true, msg, mGeckoChild, WidgetMouseEvent::eReal); @@ -2885,7 +3002,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] return; } - WidgetMouseEvent geckoEvent(true, eMouseMove, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eMouseMove, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent]; mGeckoChild->DispatchInputEvent(&geckoEvent); @@ -2901,13 +3019,15 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] return; } - WidgetMouseEvent geckoEvent(true, eMouseMove, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eMouseMove, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent]; mGeckoChild->DispatchInputEvent(&geckoEvent); - // Note, sending the above event might have destroyed our widget since we didn't retain. - // Fine so long as we don't access any local variables from here on. + // Note, sending the above event might have destroyed our widget since we + // didn't retain. Fine so long as we don't access any local variables from + // here on. // XXX maybe call markedTextSelectionChanged:client: here? @@ -2927,12 +3047,14 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] } // The right mouse went down, fire off a right mouse down event to gecko - WidgetMouseEvent geckoEvent(true, eMouseDown, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eMouseDown, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent]; geckoEvent.mButton = MouseButton::eSecondary; geckoEvent.mClickCount = [theEvent clickCount]; - nsIWidget::ContentAndAPZEventStatus eventStatus = mGeckoChild->DispatchInputEvent(&geckoEvent); + nsIWidget::ContentAndAPZEventStatus eventStatus = + mGeckoChild->DispatchInputEvent(&geckoEvent); if (!mGeckoChild) return; if (!StaticPrefs::ui_context_menus_after_mouseup() && @@ -2952,18 +3074,21 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] return; } - WidgetMouseEvent geckoEvent(true, eMouseUp, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eMouseUp, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent]; geckoEvent.mButton = MouseButton::eSecondary; geckoEvent.mClickCount = [theEvent clickCount]; nsAutoRetainCocoaObject kungFuDeathGrip(self); - nsIWidget::ContentAndAPZEventStatus eventStatus = mGeckoChild->DispatchInputEvent(&geckoEvent); + nsIWidget::ContentAndAPZEventStatus eventStatus = + mGeckoChild->DispatchInputEvent(&geckoEvent); if (!mGeckoChild) return; if (StaticPrefs::ui_context_menus_after_mouseup() && eventStatus.mApzStatus != nsEventStatus_eConsumeNoDefault) { - // Let the superclass do the context menu stuff, but pretend it's rightMouseDown. + // Let the superclass do the context menu stuff, but pretend it's + // rightMouseDown. NSEvent* dupeEvent = [NSEvent mouseEventWithType:NSEventTypeRightMouseDown location:theEvent.locationInWindow modifierFlags:theEvent.modifierFlags @@ -2986,7 +3111,8 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] return; } - WidgetMouseEvent geckoEvent(true, eMouseMove, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eMouseMove, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent]; geckoEvent.mButton = MouseButton::eSecondary; @@ -2996,8 +3122,10 @@ NSEvent* gLastDragMouseDownEvent = nil; // [strong] } static bool ShouldDispatchBackForwardCommandForMouseButton(int16_t aButton) { - return (aButton == MouseButton::eX1 && Preferences::GetBool("mousebutton.4th.enabled", true)) || - (aButton == MouseButton::eX2 && Preferences::GetBool("mousebutton.5th.enabled", true)); + return (aButton == MouseButton::eX1 && + Preferences::GetBool("mousebutton.4th.enabled", true)) || + (aButton == MouseButton::eX2 && + Preferences::GetBool("mousebutton.5th.enabled", true)); } - (void)otherMouseDown:(NSEvent*)theEvent { @@ -3018,12 +3146,15 @@ static bool ShouldDispatchBackForwardCommandForMouseButton(int16_t aButton) { int16_t button = nsCocoaUtils::ButtonForEvent(theEvent); if (ShouldDispatchBackForwardCommandForMouseButton(button)) { WidgetCommandEvent appCommandEvent( - true, (button == MouseButton::eX2) ? nsGkAtoms::Forward : nsGkAtoms::Back, mGeckoChild); + true, + (button == MouseButton::eX2) ? nsGkAtoms::Forward : nsGkAtoms::Back, + mGeckoChild); mGeckoChild->DispatchWindowEvent(appCommandEvent); return; } - WidgetMouseEvent geckoEvent(true, eMouseDown, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eMouseDown, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent]; geckoEvent.mButton = button; geckoEvent.mClickCount = [theEvent clickCount]; @@ -3044,7 +3175,8 @@ static bool ShouldDispatchBackForwardCommandForMouseButton(int16_t aButton) { return; } - WidgetMouseEvent geckoEvent(true, eMouseUp, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eMouseUp, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent]; geckoEvent.mButton = button; @@ -3058,7 +3190,8 @@ static bool ShouldDispatchBackForwardCommandForMouseButton(int16_t aButton) { return; } - WidgetMouseEvent geckoEvent(true, eMouseMove, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eMouseMove, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent]; int16_t button = nsCocoaUtils::ButtonForEvent(theEvent); geckoEvent.mButton = button; @@ -3086,7 +3219,8 @@ static bool ShouldDispatchBackForwardCommandForMouseButton(int16_t aButton) { } static int32_t RoundUp(double aDouble) { - return aDouble < 0 ? static_cast(floor(aDouble)) : static_cast(ceil(aDouble)); + return aDouble < 0 ? static_cast(floor(aDouble)) + : static_cast(ceil(aDouble)); } static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { @@ -3100,11 +3234,12 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { // Starting with 10.12 however, pixel scroll events no longer accumulate // deltaX and deltaY; they just report floating point values for every // single event. So we need to do our own accumulation. - return PanGestureInput::GetIntegerDeltaForEvent([aEvent phase] == NSEventPhaseBegan, - [aEvent deltaX], [aEvent deltaY]); + return PanGestureInput::GetIntegerDeltaForEvent( + [aEvent phase] == NSEventPhaseBegan, [aEvent deltaX], [aEvent deltaY]); } - // For line scrolls, or pre-10.12, just use the rounded up value of deltaX / deltaY. + // For line scrolls, or pre-10.12, just use the rounded up value of deltaX / + // deltaY. return gfx::IntPoint(RoundUp([aEvent deltaX]), RoundUp([aEvent deltaY])); } @@ -3143,25 +3278,28 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { } RefPtr geckoChildDeathGrip(mGeckoChild); - NSPoint locationInWindow = nsCocoaUtils::EventLocationForWindow(theEvent, [self window]); + NSPoint locationInWindow = + nsCocoaUtils::EventLocationForWindow(theEvent, [self window]); // Use convertWindowCoordinatesRoundDown when converting the position to // integer screen pixels in order to ensure that coordinates which are just // inside the right / bottom edges of the window don't end up outside of the // window after rounding. - ScreenPoint position = - ViewAs([self convertWindowCoordinatesRoundDown:locationInWindow], - PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent); + ScreenPoint position = ViewAs( + [self convertWindowCoordinatesRoundDown:locationInWindow], + PixelCastJustification::LayoutDeviceIsScreenForUntransformedEvent); - bool usePreciseDeltas = [theEvent hasPreciseScrollingDeltas] && - Preferences::GetBool("mousewheel.enable_pixel_scrolling", true); + bool usePreciseDeltas = + [theEvent hasPreciseScrollingDeltas] && + Preferences::GetBool("mousewheel.enable_pixel_scrolling", true); bool hasPhaseInformation = nsCocoaUtils::EventHasPhaseInformation(theEvent); gfx::IntPoint lineOrPageDelta = -GetIntegerDeltaForEvent(theEvent); Modifiers modifiers = nsCocoaUtils::ModifiersForEvent(theEvent); - TimeStamp eventTimeStamp = nsCocoaUtils::GetEventTimeStamp([theEvent timestamp]); + TimeStamp eventTimeStamp = + nsCocoaUtils::GetEventTimeStamp([theEvent timestamp]); ScreenPoint preciseDelta; if (usePreciseDeltas) { @@ -3173,14 +3311,16 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { if (usePreciseDeltas && hasPhaseInformation) { PanGestureInput panEvent = nsCocoaUtils::CreatePanGestureEvent( - theEvent, eventTimeStamp, position, preciseDelta, lineOrPageDelta, modifiers); + theEvent, eventTimeStamp, position, preciseDelta, lineOrPageDelta, + modifiers); geckoChildDeathGrip->DispatchAPZWheelInputEvent(panEvent); } else if (usePreciseDeltas) { // This is on 10.6 or old touchpads that don't have any phase information. - ScrollWheelInput wheelEvent(eventTimeStamp, modifiers, ScrollWheelInput::SCROLLMODE_INSTANT, - ScrollWheelInput::SCROLLDELTA_PIXEL, position, preciseDelta.x, - preciseDelta.y, false, + ScrollWheelInput wheelEvent(eventTimeStamp, modifiers, + ScrollWheelInput::SCROLLMODE_INSTANT, + ScrollWheelInput::SCROLLDELTA_PIXEL, position, + preciseDelta.x, preciseDelta.y, false, // This parameter is used for wheel delta // adjustment, such as auto-dir scrolling, // but we do't need to do anything special here @@ -3196,13 +3336,15 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { wheelEvent.mIsMomentum = nsCocoaUtils::IsMomentumScrollEvent(theEvent); geckoChildDeathGrip->DispatchAPZWheelInputEvent(wheelEvent); } else { - ScrollWheelInput::ScrollMode scrollMode = ScrollWheelInput::SCROLLMODE_INSTANT; - if (StaticPrefs::general_smoothScroll() && StaticPrefs::general_smoothScroll_mouseWheel()) { + ScrollWheelInput::ScrollMode scrollMode = + ScrollWheelInput::SCROLLMODE_INSTANT; + if (StaticPrefs::general_smoothScroll() && + StaticPrefs::general_smoothScroll_mouseWheel()) { scrollMode = ScrollWheelInput::SCROLLMODE_SMOOTH; } ScrollWheelInput wheelEvent(eventTimeStamp, modifiers, scrollMode, - ScrollWheelInput::SCROLLDELTA_LINE, position, lineOrPageDelta.x, - lineOrPageDelta.y, false, + ScrollWheelInput::SCROLLDELTA_LINE, position, + lineOrPageDelta.x, lineOrPageDelta.y, false, // This parameter is used for wheel delta // adjustment, such as auto-dir scrolling, // but we do't need to do anything special here @@ -3240,7 +3382,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { if (!mGeckoChild) return nil; } - WidgetMouseEvent geckoEvent(true, eContextMenu, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eContextMenu, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent]; if (StaticPrefs::dom_event_treat_ctrl_click_as_right_click_disabled() && [theEvent type] == NSEventTypeLeftMouseDown) { @@ -3274,25 +3417,30 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { toGeckoEvent:(WidgetWheelEvent*)outWheelEvent { [self convertCocoaMouseEvent:aMouseEvent toGeckoEvent:outWheelEvent]; - bool usePreciseDeltas = [aMouseEvent hasPreciseScrollingDeltas] && - Preferences::GetBool("mousewheel.enable_pixel_scrolling", true); + bool usePreciseDeltas = + [aMouseEvent hasPreciseScrollingDeltas] && + Preferences::GetBool("mousewheel.enable_pixel_scrolling", true); - outWheelEvent->mDeltaMode = usePreciseDeltas ? dom::WheelEvent_Binding::DOM_DELTA_PIXEL - : dom::WheelEvent_Binding::DOM_DELTA_LINE; + outWheelEvent->mDeltaMode = usePreciseDeltas + ? dom::WheelEvent_Binding::DOM_DELTA_PIXEL + : dom::WheelEvent_Binding::DOM_DELTA_LINE; outWheelEvent->mIsMomentum = nsCocoaUtils::IsMomentumScrollEvent(aMouseEvent); } -- (void)convertCocoaMouseEvent:(NSEvent*)aMouseEvent toGeckoEvent:(WidgetInputEvent*)outGeckoEvent { +- (void)convertCocoaMouseEvent:(NSEvent*)aMouseEvent + toGeckoEvent:(WidgetInputEvent*)outGeckoEvent { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - NS_ASSERTION(outGeckoEvent, - "convertCocoaMouseEvent:toGeckoEvent: requires non-null aoutGeckoEvent"); + NS_ASSERTION( + outGeckoEvent, + "convertCocoaMouseEvent:toGeckoEvent: requires non-null aoutGeckoEvent"); if (!outGeckoEvent) return; nsCocoaUtils::InitInputEvent(*outGeckoEvent, aMouseEvent); // convert point to view coordinate system - NSPoint locationInWindow = nsCocoaUtils::EventLocationForWindow(aMouseEvent, [self window]); + NSPoint locationInWindow = + nsCocoaUtils::EventLocationForWindow(aMouseEvent, [self window]); outGeckoEvent->mRefPoint = [self convertWindowCoordinates:locationInWindow]; @@ -3328,7 +3476,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { case NSEventTypeOtherMouseDragged: case NSEventTypeMouseMoved: if ([aMouseEvent subtype] == NSEventSubtypeTabletPoint) { - [self convertCocoaTabletPointerEvent:aMouseEvent toGeckoEvent:mouseEvent->AsMouseEvent()]; + [self convertCocoaTabletPointerEvent:aMouseEvent + toGeckoEvent:mouseEvent->AsMouseEvent()]; } break; @@ -3348,7 +3497,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { } if ([aPointerEvent type] != NSEventTypeMouseMoved) { aOutGeckoEvent->mPressure = [aPointerEvent pressure]; - MOZ_ASSERT(aOutGeckoEvent->mPressure >= 0.0 && aOutGeckoEvent->mPressure <= 1.0); + MOZ_ASSERT(aOutGeckoEvent->mPressure >= 0.0 && + aOutGeckoEvent->mPressure <= 1.0); } aOutGeckoEvent->mInputSource = dom::MouseEvent_Binding::MOZ_SOURCE_PEN; aOutGeckoEvent->tiltX = (int32_t)lround([aPointerEvent tilt].x * 90); @@ -3475,19 +3625,23 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { } - (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)aRange - actualRange:(NSRangePointer)actualRange { + actualRange: + (NSRangePointer)actualRange { NS_ENSURE_TRUE(mTextInputHandler, nil); - return mTextInputHandler->GetAttributedSubstringFromRange(aRange, actualRange); + return mTextInputHandler->GetAttributedSubstringFromRange(aRange, + actualRange); } -- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange { +- (NSRect)firstRectForCharacterRange:(NSRange)aRange + actualRange:(NSRangePointer)actualRange { NS_ENSURE_TRUE(mTextInputHandler, NSMakeRect(0.0, 0.0, 0.0, 0.0)); return mTextInputHandler->FirstRectForCharacterRange(aRange, actualRange); } - (void)quickLookWithEvent:(NSEvent*)event { // Show dictionary by current point - WidgetContentCommandEvent contentCommandEvent(true, eContentCommandLookUpDictionary, mGeckoChild); + WidgetContentCommandEvent contentCommandEvent( + true, eContentCommandLookUpDictionary, mGeckoChild); NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil]; contentCommandEvent.mRefPoint = mGeckoChild->CocoaPointsToDevPixels(point); mGeckoChild->DispatchWindowEvent(contentCommandEvent); @@ -3506,9 +3660,10 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { #pragma mark - // This is a private API that Cocoa uses. -// Cocoa will call this after the menu system returns "NO" for "performKeyEquivalent:". -// We want all they key events we can get so just return YES. In particular, this fixes -// ctrl-tab - we don't get a "keyDown:" call for that without this. +// Cocoa will call this after the menu system returns "NO" for +// "performKeyEquivalent:". We want all they key events we can get so just +// return YES. In particular, this fixes ctrl-tab - we don't get a "keyDown:" +// call for that without this. - (BOOL)_wantsKeyDownForEvent:(NSEvent*)event { return YES; } @@ -3536,32 +3691,36 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { } #if !defined(RELEASE_OR_BETA) || defined(DEBUG) - if (!Preferences::GetBool("intl.allow-insecure-text-input", false) && mGeckoChild && - mTextInputHandler && mTextInputHandler->IsFocused()) { + if (!Preferences::GetBool("intl.allow-insecure-text-input", false) && + mGeckoChild && mTextInputHandler && mTextInputHandler->IsFocused()) { NSWindow* window = [self window]; NSString* info = [NSString - stringWithFormat: - @"\nview [%@], window [%@], window is key %i, is fullscreen %i, app is active %i", self, - window, [window isKeyWindow], ([window styleMask] & NSWindowStyleMaskFullScreen) != 0, - [NSApp isActive]]; + stringWithFormat:@"\nview [%@], window [%@], window is key %i, is " + @"fullscreen %i, app is active %i", + self, window, [window isKeyWindow], + ([window styleMask] & NSWindowStyleMaskFullScreen) != + 0, + [NSApp isActive]]; nsAutoCString additionalInfo([info UTF8String]); if (mGeckoChild->GetInputContext().IsPasswordEditor() && !TextInputHandler::IsSecureEventInputEnabled()) { -# define CRASH_MESSAGE "A password editor has focus, but not in secure input mode" +# define CRASH_MESSAGE \ + "A password editor has focus, but not in secure input mode" - CrashReporter::AppendAppNotesToCrashReport("\nBug 893973: "_ns + - nsLiteralCString(CRASH_MESSAGE)); + CrashReporter::AppendAppNotesToCrashReport( + "\nBug 893973: "_ns + nsLiteralCString(CRASH_MESSAGE)); CrashReporter::AppendAppNotesToCrashReport(additionalInfo); MOZ_CRASH(CRASH_MESSAGE); # undef CRASH_MESSAGE } else if (!mGeckoChild->GetInputContext().IsPasswordEditor() && TextInputHandler::IsSecureEventInputEnabled()) { -# define CRASH_MESSAGE "A non-password editor has focus, but in secure input mode" +# define CRASH_MESSAGE \ + "A non-password editor has focus, but in secure input mode" - CrashReporter::AppendAppNotesToCrashReport("\nBug 893973: "_ns + - nsLiteralCString(CRASH_MESSAGE)); + CrashReporter::AppendAppNotesToCrashReport( + "\nBug 893973: "_ns + nsLiteralCString(CRASH_MESSAGE)); CrashReporter::AppendAppNotesToCrashReport(additionalInfo); MOZ_CRASH(CRASH_MESSAGE); @@ -3897,7 +4056,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { // If we're being destroyed assume the default -- return YES. if (!mGeckoChild) return YES; - WidgetMouseEvent geckoEvent(true, eMouseActivate, mGeckoChild, WidgetMouseEvent::eReal); + WidgetMouseEvent geckoEvent(true, eMouseActivate, mGeckoChild, + WidgetMouseEvent::eReal); [self convertCocoaMouseEvent:aEvent toGeckoEvent:&geckoEvent]; return (mGeckoChild->DispatchInputEvent(&geckoEvent).mContentStatus != nsEventStatus_eConsumeNoDefault); @@ -3924,7 +4084,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { // allows embedders to avoid re-entrant calls to -makeKeyAndOrderFront, // which can happen because these activate calls propagate out // to the embedder via nsIEmbeddingSiteWindow::SetFocus(). - BOOL isMozWindow = [[self window] respondsToSelector:@selector(setSuppressMakeKeyFront:)]; + BOOL isMozWindow = + [[self window] respondsToSelector:@selector(setSuppressMakeKeyFront:)]; if (isMozWindow) [[self window] setSuppressMakeKeyFront:YES]; nsIWidgetListener* listener = mGeckoChild->GetWidgetListener(); @@ -3976,9 +4137,12 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { #define kDragServiceContractID "@mozilla.org/widget/dragservice;1" - (NSDragOperation)dragOperationFromDragAction:(int32_t)aDragAction { - if (nsIDragService::DRAGDROP_ACTION_LINK & aDragAction) return NSDragOperationLink; - if (nsIDragService::DRAGDROP_ACTION_COPY & aDragAction) return NSDragOperationCopy; - if (nsIDragService::DRAGDROP_ACTION_MOVE & aDragAction) return NSDragOperationGeneric; + if (nsIDragService::DRAGDROP_ACTION_LINK & aDragAction) + return NSDragOperationLink; + if (nsIDragService::DRAGDROP_ACTION_COPY & aDragAction) + return NSDragOperationCopy; + if (nsIDragService::DRAGDROP_ACTION_MOVE & aDragAction) + return NSDragOperationGeneric; return NSDragOperationNone; } @@ -4027,8 +4191,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { // fire the drag event at the source. Just ignore whether it was // cancelled or not as there isn't actually a means to stop the drag nsCOMPtr dragService = mDragService; - dragService->FireDragEventAtSource(eDrag, - nsCocoaUtils::ModifiersForEvent([NSApp currentEvent])); + dragService->FireDragEventAtSource( + eDrag, nsCocoaUtils::ModifiersForEvent([NSApp currentEvent])); dragSession->SetCanDrop(false); } else if (aMessage == eDrop) { // We make the assumption that the dragOver handlers have correctly set @@ -4041,7 +4205,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { dragSession->GetSourceNode(getter_AddRefs(sourceNode)); if (!sourceNode) { nsCOMPtr dragService = mDragService; - dragService->EndDragSession(false, nsCocoaUtils::ModifiersForEvent([NSApp currentEvent])); + dragService->EndDragSession( + false, nsCocoaUtils::ModifiersForEvent([NSApp currentEvent])); } return NSDragOperationNone; } @@ -4102,7 +4267,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { // since we're done with it for now (until the user // drags back into mozilla). nsCOMPtr dragService = mDragService; - dragService->EndDragSession(false, nsCocoaUtils::ModifiersForEvent([NSApp currentEvent])); + dragService->EndDragSession( + false, nsCocoaUtils::ModifiersForEvent([NSApp currentEvent])); } break; } @@ -4184,8 +4350,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { gDraggedTransferables = nullptr; NSEvent* currentEvent = [NSApp currentEvent]; - gUserCancelledDrag = - ([currentEvent type] == NSEventTypeKeyDown && [currentEvent keyCode] == kVK_Escape); + gUserCancelledDrag = ([currentEvent type] == NSEventTypeKeyDown && + [currentEvent keyCode] == kVK_Escape); if (!mDragService) { CallGetService(kDragServiceContractID, &mDragService); @@ -4193,16 +4359,19 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { } if (mDragService) { - RefPtr dragService = static_cast(mDragService); + RefPtr dragService = + static_cast(mDragService); // Set the dragend point from the current mouse location // FIXME(emilio): Weird that we wouldn't use aPoint instead? Seems to work // locally as well... // NSPoint pnt = aPoint; NSPoint pnt = [NSEvent mouseLocation]; - NSPoint locationInWindow = nsCocoaUtils::ConvertPointFromScreen([self window], pnt); + NSPoint locationInWindow = + nsCocoaUtils::ConvertPointFromScreen([self window], pnt); FlipCocoaScreenCoordinate(pnt); - dragService->SetDragEndPoint([self convertWindowCoordinates:locationInWindow]); + dragService->SetDragEndPoint( + [self convertWindowCoordinates:locationInWindow]); // XXX: dropEffect should be updated per |aOperation|. // As things stand though, |aOperation| isn't well handled within "our" @@ -4219,7 +4388,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { } } - dragService->EndDragSession(true, nsCocoaUtils::ModifiersForEvent(currentEvent)); + dragService->EndDragSession(true, + nsCocoaUtils::ModifiersForEvent(currentEvent)); NS_RELEASE(mDragService); } @@ -4233,7 +4403,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { } // NSDraggingSource -- (void)draggingSession:(NSDraggingSession*)aSession movedToPoint:(NSPoint)aPoint { +- (void)draggingSession:(NSDraggingSession*)aSession + movedToPoint:(NSPoint)aPoint { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; // Get the drag service if it isn't already cached. The drag service @@ -4252,7 +4423,8 @@ static gfx::IntPoint GetIntegerDeltaForEvent(NSEvent* aEvent) { } // NSDraggingSource -- (void)draggingSession:(NSDraggingSession*)aSession willBeginAtPoint:(NSPoint)aPoint { +- (void)draggingSession:(NSDraggingSession*)aSession + willBeginAtPoint:(NSPoint)aPoint { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; // there should never be a globalDragPboard when "willBeginAtPoint:" is @@ -4301,7 +4473,8 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { gDraggedTransferables->GetLength(&count); for (uint32_t j = 0; j < count; j++) { - nsCOMPtr currentTransferable = do_QueryElementAt(gDraggedTransferables, j); + nsCOMPtr currentTransferable = + do_QueryElementAt(gDraggedTransferables, j); if (!currentTransferable) { return; } @@ -4320,29 +4493,47 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { [types addObject:[UTIHelper stringFromPboardType:kMozWildcardPboardType]]; for (unsigned int k = 0; k < typeCount; k++) { NSString* curType = [types objectAtIndex:k]; - if ([curType isEqualToString:[UTIHelper stringFromPboardType:NSPasteboardTypeString]] || - [curType isEqualToString:[UTIHelper stringFromPboardType:kPublicUrlPboardType]] || - [curType isEqualToString:[UTIHelper stringFromPboardType:kPublicUrlNamePboardType]] || - [curType isEqualToString:[UTIHelper stringFromPboardType:(NSString*)kUTTypeFileURL]]) { - [aPasteboard setString:[pasteboardOutputDict valueForKey:curType] forType:curType]; + if ([curType isEqualToString:[UTIHelper stringFromPboardType: + NSPasteboardTypeString]] || + [curType + isEqualToString:[UTIHelper + stringFromPboardType:kPublicUrlPboardType]] || + [curType isEqualToString:[UTIHelper stringFromPboardType: + kPublicUrlNamePboardType]] || + [curType + isEqualToString:[UTIHelper + stringFromPboardType:(NSString*) + kUTTypeFileURL]]) { + [aPasteboard setString:[pasteboardOutputDict valueForKey:curType] + forType:curType]; + } else if ([curType isEqualToString:[UTIHelper + stringFromPboardType: + kUrlsWithTitlesPboardType]]) { + [aPasteboard setPropertyList:[pasteboardOutputDict valueForKey:curType] + forType:curType]; } else if ([curType - isEqualToString:[UTIHelper stringFromPboardType:kUrlsWithTitlesPboardType]]) { - [aPasteboard setPropertyList:[pasteboardOutputDict valueForKey:curType] forType:curType]; - } else if ([curType isEqualToString:[UTIHelper stringFromPboardType:NSPasteboardTypeHTML]]) { + isEqualToString:[UTIHelper stringFromPboardType: + NSPasteboardTypeHTML]]) { [aPasteboard setString:(nsClipboard::WrapHtmlForSystemPasteboard( [pasteboardOutputDict valueForKey:curType])) forType:curType]; - } else if ([curType isEqualToString:[UTIHelper stringFromPboardType:NSPasteboardTypeTIFF]] || - [curType - isEqualToString:[UTIHelper stringFromPboardType:kMozCustomTypesPboardType]]) { - [aPasteboard setData:[pasteboardOutputDict valueForKey:curType] forType:curType]; } else if ([curType - isEqualToString:[UTIHelper stringFromPboardType:kMozFileUrlsPboardType]]) { + isEqualToString:[UTIHelper stringFromPboardType: + NSPasteboardTypeTIFF]] || + [curType isEqualToString:[UTIHelper + stringFromPboardType: + kMozCustomTypesPboardType]]) { + [aPasteboard setData:[pasteboardOutputDict valueForKey:curType] + forType:curType]; + } else if ([curType + isEqualToString:[UTIHelper stringFromPboardType: + kMozFileUrlsPboardType]]) { [aPasteboard writeObjects:[pasteboardOutputDict valueForKey:curType]]; } else if ([curType - isEqualToString:[UTIHelper - stringFromPboardType:(NSString*) - kPasteboardTypeFileURLPromise]]) { + isEqualToString: + [UTIHelper + stringFromPboardType: + (NSString*)kPasteboardTypeFileURLPromise]]) { nsCOMPtr targFile; NS_NewLocalFile(u""_ns, true, getter_AddRefs(targFile)); nsCOMPtr macLocalFile = do_QueryInterface(targFile); @@ -4372,7 +4563,8 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { } for (uint32_t i = 0; i < transferableCount; i++) { - nsCOMPtr item = do_QueryElementAt(gDraggedTransferables, i); + nsCOMPtr item = + do_QueryElementAt(gDraggedTransferables, i); if (!item) { NS_ERROR("no transferable"); continue; @@ -4383,10 +4575,12 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { // Now request the kFilePromiseMime data, which will invoke the data // provider. If successful, the file will have been created. nsCOMPtr fileDataPrimitive; - Unused << item->GetTransferData(kFilePromiseMime, getter_AddRefs(fileDataPrimitive)); + Unused << item->GetTransferData(kFilePromiseMime, + getter_AddRefs(fileDataPrimitive)); } - [aPasteboard setPropertyList:[pasteboardOutputDict valueForKey:curType] forType:curType]; + [aPasteboard setPropertyList:[pasteboardOutputDict valueForKey:curType] + forType:curType]; } } } @@ -4398,9 +4592,10 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { // Support for the "Services" menu. We currently only support sending strings // and HTML to system services. -// This method can be called on any thread (see bug 1751687). We can only usefully -// handle it on the main thread. -- (id)validRequestorForSendType:(NSString*)sendType returnType:(NSString*)returnType { +// This method can be called on any thread (see bug 1751687). We can only +// usefully handle it on the main thread. +- (id)validRequestorForSendType:(NSString*)sendType + returnType:(NSString*)returnType { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; if (!NS_IsMainThread()) { @@ -4424,9 +4619,11 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { id result = nil; - NSString* stringType = [UTIHelper stringFromPboardType:NSPasteboardTypeString]; + NSString* stringType = + [UTIHelper stringFromPboardType:NSPasteboardTypeString]; NSString* htmlType = [UTIHelper stringFromPboardType:NSPasteboardTypeHTML]; - if ((!sendType || [sendType isEqualToString:stringType] || [sendType isEqualToString:htmlType]) && + if ((!sendType || [sendType isEqualToString:stringType] || + [sendType isEqualToString:htmlType]) && (!returnType || [returnType isEqualToString:stringType] || [returnType isEqualToString:htmlType])) { if (mGeckoChild) { @@ -4445,17 +4642,19 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { // Determine if we can paste (if receiving data from the service). if (mGeckoChild && returnType) { - WidgetContentCommandEvent command(true, eContentCommandPasteTransferable, mGeckoChild, - true); + WidgetContentCommandEvent command( + true, eContentCommandPasteTransferable, mGeckoChild, true); // This might possibly destroy our widget (and null out mGeckoChild). mGeckoChild->DispatchWindowEvent(command); - if (!mGeckoChild || !command.mSucceeded || !command.mIsEnabled) result = nil; + if (!mGeckoChild || !command.mSucceeded || !command.mIsEnabled) + result = nil; } } } // Give the superclass a chance if this object will not handle this request. - if (!result) result = [super validRequestorForSendType:sendType returnType:returnType]; + if (!result) + result = [super validRequestorForSendType:sendType returnType:returnType]; return result; @@ -4468,9 +4667,13 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { nsAutoRetainCocoaObject kungFuDeathGrip(self); // Make sure that the service will accept strings or HTML. - if (![types containsObject:[UTIHelper stringFromPboardType:NSStringPboardType]] && - ![types containsObject:[UTIHelper stringFromPboardType:NSPasteboardTypeString]] && - ![types containsObject:[UTIHelper stringFromPboardType:NSPasteboardTypeHTML]]) { + if (![types + containsObject:[UTIHelper stringFromPboardType:NSStringPboardType]] && + ![types + containsObject:[UTIHelper + stringFromPboardType:NSPasteboardTypeString]] && + ![types containsObject:[UTIHelper + stringFromPboardType:NSPasteboardTypeHTML]]) { return NO; } @@ -4480,7 +4683,8 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { // Transform the transferable to an NSDictionary. NSDictionary* pasteboardOutputDict = nullptr; - pasteboardOutputDict = nsClipboard::PasteboardDictFromTransferable(nsClipboard::sSelectionCache); + pasteboardOutputDict = + nsClipboard::PasteboardDictFromTransferable(nsClipboard::sSelectionCache); if (!pasteboardOutputDict) return NO; @@ -4495,21 +4699,32 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { NSString* currentKey = [declaredTypes objectAtIndex:i]; id currentValue = [pasteboardOutputDict valueForKey:currentKey]; - if ([currentKey isEqualToString:[UTIHelper stringFromPboardType:NSPasteboardTypeString]] || - [currentKey isEqualToString:[UTIHelper stringFromPboardType:kPublicUrlPboardType]] || - [currentKey isEqualToString:[UTIHelper stringFromPboardType:kPublicUrlNamePboardType]]) { + if ([currentKey + isEqualToString:[UTIHelper + stringFromPboardType:NSPasteboardTypeString]] || + [currentKey + isEqualToString:[UTIHelper + stringFromPboardType:kPublicUrlPboardType]] || + [currentKey isEqualToString:[UTIHelper stringFromPboardType: + kPublicUrlNamePboardType]]) { [pboard setString:currentValue forType:currentKey]; - } else if ([currentKey isEqualToString:[UTIHelper stringFromPboardType:NSPasteboardTypeHTML]]) { + } else if ([currentKey + isEqualToString: + [UTIHelper stringFromPboardType:NSPasteboardTypeHTML]]) { [pboard setString:(nsClipboard::WrapHtmlForSystemPasteboard(currentValue)) forType:currentKey]; - } else if ([currentKey isEqualToString:[UTIHelper stringFromPboardType:NSPasteboardTypeTIFF]]) { + } else if ([currentKey + isEqualToString: + [UTIHelper stringFromPboardType:NSPasteboardTypeTIFF]]) { [pboard setData:currentValue forType:currentKey]; } else if ([currentKey - isEqualToString:[UTIHelper - stringFromPboardType:(NSString*) - kPasteboardTypeFileURLPromise]] || + isEqualToString: + [UTIHelper + stringFromPboardType: + (NSString*)kPasteboardTypeFileURLPromise]] || [currentKey - isEqualToString:[UTIHelper stringFromPboardType:kUrlsWithTitlesPboardType]]) { + isEqualToString:[UTIHelper stringFromPboardType: + kUrlsWithTitlesPboardType]]) { [pboard setPropertyList:currentValue forType:currentKey]; } } @@ -4521,7 +4736,8 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { // Called if the service wants us to replace the current selection. - (BOOL)readSelectionFromPasteboard:(NSPasteboard*)pboard { nsresult rv; - nsCOMPtr trans = do_CreateInstance("@mozilla.org/widget/transferable;1", &rv); + nsCOMPtr trans = + do_CreateInstance("@mozilla.org/widget/transferable;1", &rv); if (NS_FAILED(rv)) return NO; trans->Init(nullptr); @@ -4533,7 +4749,8 @@ static CFTypeRefPtr GetPasteLocation(NSPasteboard* aPasteboard) { NS_ENSURE_TRUE(mGeckoChild, false); - WidgetContentCommandEvent command(true, eContentCommandPasteTransferable, mGeckoChild); + WidgetContentCommandEvent command(true, eContentCommandPasteTransferable, + mGeckoChild); command.mTransferable = trans; mGeckoChild->DispatchWindowEvent(command); @@ -4567,7 +4784,8 @@ nsresult nsChildView::GetSelectionAsPlaintext(nsAString& aResult) { // Get the current chrome or content selection. NSDictionary* pasteboardOutputDict = nullptr; - pasteboardOutputDict = nsClipboard::PasteboardDictFromTransferable(nsClipboard::sSelectionCache); + pasteboardOutputDict = + nsClipboard::PasteboardDictFromTransferable(nsClipboard::sSelectionCache); if (NS_WARN_IF(!pasteboardOutputDict)) { return NS_ERROR_FAILURE; @@ -4611,8 +4829,8 @@ nsresult nsChildView::RestoreHiDPIMode() { the heavy lifting. The topmost ChildView corresponds to a mozRootAccessible object. - All ChildView needs to do is to route all accessibility calls (from the NSAccessibility APIs) - down to its object, pretending that they are the same. + All ChildView needs to do is to route all accessibility calls (from the + NSAccessibility APIs) down to its object, pretending that they are the same. */ - (id)accessible { if (!mGeckoChild) return nil; @@ -4621,7 +4839,8 @@ nsresult nsChildView::RestoreHiDPIMode() { nsAutoRetainCocoaObject kungFuDeathGrip(self); RefPtr geckoChild(mGeckoChild); - RefPtr accessible = geckoChild->GetDocumentAccessible(); + RefPtr accessible = + geckoChild->GetDocumentAccessible(); if (!accessible) return nil; accessible->GetNativeInterface((void**)&nativeAccessible); @@ -4653,19 +4872,22 @@ nsresult nsChildView::RestoreHiDPIMode() { // general - (BOOL)isAccessibilityElement { - if (!mozilla::a11y::ShouldA11yBeEnabled()) return [super isAccessibilityElement]; + if (!mozilla::a11y::ShouldA11yBeEnabled()) + return [super isAccessibilityElement]; return [[self accessible] isAccessibilityElement]; } - (id)accessibilityHitTest:(NSPoint)point { - if (!mozilla::a11y::ShouldA11yBeEnabled()) return [super accessibilityHitTest:point]; + if (!mozilla::a11y::ShouldA11yBeEnabled()) + return [super accessibilityHitTest:point]; return [[self accessible] accessibilityHitTest:point]; } - (id)accessibilityFocusedUIElement { - if (!mozilla::a11y::ShouldA11yBeEnabled()) return [super accessibilityFocusedUIElement]; + if (!mozilla::a11y::ShouldA11yBeEnabled()) + return [super accessibilityFocusedUIElement]; return [[self accessible] accessibilityFocusedUIElement]; } @@ -4673,19 +4895,22 @@ nsresult nsChildView::RestoreHiDPIMode() { // actions - (NSArray*)accessibilityActionNames { - if (!mozilla::a11y::ShouldA11yBeEnabled()) return [super accessibilityActionNames]; + if (!mozilla::a11y::ShouldA11yBeEnabled()) + return [super accessibilityActionNames]; return [[self accessible] accessibilityActionNames]; } - (NSString*)accessibilityActionDescription:(NSString*)action { - if (!mozilla::a11y::ShouldA11yBeEnabled()) return [super accessibilityActionDescription:action]; + if (!mozilla::a11y::ShouldA11yBeEnabled()) + return [super accessibilityActionDescription:action]; return [[self accessible] accessibilityActionDescription:action]; } - (void)accessibilityPerformAction:(NSString*)action { - if (!mozilla::a11y::ShouldA11yBeEnabled()) return [super accessibilityPerformAction:action]; + if (!mozilla::a11y::ShouldA11yBeEnabled()) + return [super accessibilityPerformAction:action]; return [[self accessible] accessibilityPerformAction:action]; } @@ -4693,7 +4918,8 @@ nsresult nsChildView::RestoreHiDPIMode() { // attributes - (NSArray*)accessibilityAttributeNames { - if (!mozilla::a11y::ShouldA11yBeEnabled()) return [super accessibilityAttributeNames]; + if (!mozilla::a11y::ShouldA11yBeEnabled()) + return [super accessibilityAttributeNames]; return [[self accessible] accessibilityAttributeNames]; } @@ -4708,14 +4934,16 @@ nsresult nsChildView::RestoreHiDPIMode() { - (id)accessibilityAttributeValue:(NSString*)attribute { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - if (!mozilla::a11y::ShouldA11yBeEnabled()) return [super accessibilityAttributeValue:attribute]; + if (!mozilla::a11y::ShouldA11yBeEnabled()) + return [super accessibilityAttributeValue:attribute]; id accessible = [self accessible]; - // if we're the root (topmost) accessible, we need to return our native AXParent as we - // traverse outside to the hierarchy of whoever embeds us. thus, fall back on NSView's - // default implementation for this attribute. - if ([attribute isEqualToString:NSAccessibilityParentAttribute] && [accessible isRoot]) { + // if we're the root (topmost) accessible, we need to return our native + // AXParent as we traverse outside to the hierarchy of whoever embeds us. + // thus, fall back on NSView's default implementation for this attribute. + if ([attribute isEqualToString:NSAccessibilityParentAttribute] && + [accessible isRoot]) { id parentAccessible = [super accessibilityAttributeValue:attribute]; return parentAccessible; } @@ -4733,7 +4961,8 @@ nsresult nsChildView::RestoreHiDPIMode() { + (NSMutableDictionary*)sNativeKeyEventsMap { // This dictionary is "leaked". - static NSMutableDictionary* sNativeKeyEventsMap = [[NSMutableDictionary alloc] init]; + static NSMutableDictionary* sNativeKeyEventsMap = + [[NSMutableDictionary alloc] init]; return sNativeKeyEventsMap; } @@ -4759,7 +4988,8 @@ nsresult nsChildView::RestoreHiDPIMode() { } - (void)drawRect:(NSRect)aRect { - NS_WARNING("Unexpected call to drawRect: This view returns YES from wantsUpdateLayer, so " + NS_WARNING("Unexpected call to drawRect: This view returns YES from " + "wantsUpdateLayer, so " "drawRect should not be called."); } @@ -4809,38 +5039,44 @@ void ChildViewMouseTracker::MouseExitedWindow(NSEvent* aEvent) { void ChildViewMouseTracker::NativeMenuOpened() { // Send a mouse exit event now. - // The menu consumes all mouse events while it's open, and we don't want to be stuck thinking the - // mouse is still hovering our window after the mouse has already moved. This could result in - // unintended cursor changes or tooltips. + // The menu consumes all mouse events while it's open, and we don't want to be + // stuck thinking the mouse is still hovering our window after the mouse has + // already moved. This could result in unintended cursor changes or tooltips. sWindowUnderMouse = nil; ReEvaluateMouseEnterState(nil); } void ChildViewMouseTracker::NativeMenuClosed() { - // If a window was hovered before the menu opened, re-enter that window at the last known mouse - // position. - // After -[NSView didCloseMenu:withEvent:] is called, any NSTrackingArea updates that were - // buffered while the menu was open will be replayed. + // If a window was hovered before the menu opened, re-enter that window at the + // last known mouse position. After -[NSView didCloseMenu:withEvent:] is + // called, any NSTrackingArea updates that were buffered while the menu was + // open will be replayed. if (sLastMouseMoveEvent) { sWindowUnderMouse = sLastMouseMoveEvent.window; ReEvaluateMouseEnterState(sLastMouseMoveEvent); } } -void ChildViewMouseTracker::ReEvaluateMouseEnterState(NSEvent* aEvent, ChildView* aOldView) { +void ChildViewMouseTracker::ReEvaluateMouseEnterState(NSEvent* aEvent, + ChildView* aOldView) { ChildView* oldView = aOldView ? aOldView : sLastMouseEventView; sLastMouseEventView = ViewForEvent(aEvent); if (sLastMouseEventView != oldView) { // Send enter and / or exit events. - WidgetMouseEvent::ExitFrom exitFrom = [sLastMouseEventView window] == [oldView window] - ? WidgetMouseEvent::ePlatformChild - : WidgetMouseEvent::ePlatformTopLevel; + WidgetMouseEvent::ExitFrom exitFrom = + [sLastMouseEventView window] == [oldView window] + ? WidgetMouseEvent::ePlatformChild + : WidgetMouseEvent::ePlatformTopLevel; [oldView sendMouseEnterOrExitEvent:aEvent enter:NO exitFrom:exitFrom]; - // After the cursor exits the window set it to a visible regular arrow cursor. + // After the cursor exits the window set it to a visible regular arrow + // cursor. if (exitFrom == WidgetMouseEvent::ePlatformTopLevel) { - [[nsCursorManager sharedInstance] setNonCustomCursor:nsIWidget::Cursor{eCursor_standard}]; + [[nsCursorManager sharedInstance] + setNonCustomCursor:nsIWidget::Cursor{eCursor_standard}]; } - [sLastMouseEventView sendMouseEnterOrExitEvent:aEvent enter:YES exitFrom:exitFrom]; + [sLastMouseEventView sendMouseEnterOrExitEvent:aEvent + enter:YES + exitFrom:exitFrom]; } } @@ -4862,7 +5098,8 @@ void ChildViewMouseTracker::MouseMoved(NSEvent* aEvent) { void ChildViewMouseTracker::MouseScrolled(NSEvent* aEvent) { if (!nsCocoaUtils::IsMomentumScrollEvent(aEvent)) { // Store the position so we can pin future momentum scroll events. - sLastScrollEventScreenLocation = nsCocoaUtils::ScreenLocationForEvent(aEvent); + sLastScrollEventScreenLocation = + nsCocoaUtils::ScreenLocationForEvent(aEvent); } } @@ -4870,7 +5107,8 @@ ChildView* ChildViewMouseTracker::ViewForEvent(NSEvent* aEvent) { NSWindow* window = sWindowUnderMouse; if (!window) return nil; - NSPoint windowEventLocation = nsCocoaUtils::EventLocationForWindow(aEvent, window); + NSPoint windowEventLocation = + nsCocoaUtils::EventLocationForWindow(aEvent, window); NSView* view = [[[window contentView] superview] hitTest:windowEventLocation]; if (![view isKindOfClass:[ChildView class]]) return nil; @@ -4881,7 +5119,9 @@ ChildView* ChildViewMouseTracker::ViewForEvent(NSEvent* aEvent) { return WindowAcceptsEvent(window, aEvent, childView) ? childView : nil; } -BOOL ChildViewMouseTracker::WindowAcceptsEvent(NSWindow* aWindow, NSEvent* aEvent, ChildView* aView, +BOOL ChildViewMouseTracker::WindowAcceptsEvent(NSWindow* aWindow, + NSEvent* aEvent, + ChildView* aView, BOOL aIsClickThrough) { // Right mouse down events may get through to all windows, even to a top level // window with an open sheet. @@ -4901,7 +5141,8 @@ BOOL ChildViewMouseTracker::WindowAcceptsEvent(NSWindow* aWindow, NSEvent* aEven // accept mouse move events on context menus even when none of our windows // is active, which is the right thing to do. // For panels, the parent window is the XUL window that owns the panel. - return WindowAcceptsEvent([aWindow parentWindow], aEvent, aView, aIsClickThrough); + return WindowAcceptsEvent([aWindow parentWindow], aEvent, aView, + aIsClickThrough); case WindowType::TopLevel: case WindowType::Dialog: diff --git a/widget/cocoa/nsClipboard.mm b/widget/cocoa/nsClipboard.mm index ce74d7a995ba..913396f7656b 100644 --- a/widget/cocoa/nsClipboard.mm +++ b/widget/cocoa/nsClipboard.mm @@ -32,9 +32,10 @@ mozilla::StaticRefPtr nsClipboard::sSelectionCache; int32_t nsClipboard::sSelectionCacheChangeCount = 0; nsClipboard::nsClipboard() - : nsBaseClipboard(mozilla::dom::ClipboardCapabilities(false /* supportsSelectionClipboard */, - true /* supportsFindClipboard */, - true /* supportsSelectionCache */)) {} + : nsBaseClipboard(mozilla::dom::ClipboardCapabilities( + false /* supportsSelectionClipboard */, + true /* supportsFindClipboard */, + true /* supportsSelectionCache */)) {} nsClipboard::~nsClipboard() { ClearSelectionCache(); } @@ -45,15 +46,16 @@ namespace { // We separate this into its own function because after an @try, all local // variables within that function get marked as volatile, and our C++ type // system doesn't like volatile things. -static NSData* GetDataFromPasteboard(NSPasteboard* aPasteboard, NSString* aType) { +static NSData* GetDataFromPasteboard(NSPasteboard* aPasteboard, + NSString* aType) { NSData* data = nil; @try { data = [aPasteboard dataForType:aType]; } @catch (NSException* e) { - NS_WARNING( - nsPrintfCString("Exception raised while getting data from the pasteboard: \"%s - %s\"", - [[e name] UTF8String], [[e reason] UTF8String]) - .get()); + NS_WARNING(nsPrintfCString("Exception raised while getting data from the " + "pasteboard: \"%s - %s\"", + [[e name] UTF8String], [[e reason] UTF8String]) + .get()); mozilla::Unused << e; } return data; @@ -80,7 +82,8 @@ void nsClipboard::SetSelectionCache(nsITransferable* aTransferable) { void nsClipboard::ClearSelectionCache() { SetSelectionCache(nullptr); } NS_IMETHODIMP -nsClipboard::SetNativeClipboardData(nsITransferable* aTransferable, nsIClipboardOwner* aOwner, +nsClipboard::SetNativeClipboardData(nsITransferable* aTransferable, + nsIClipboardOwner* aOwner, int32_t aWhichClipboard) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; @@ -92,7 +95,8 @@ nsClipboard::SetNativeClipboardData(nsITransferable* aTransferable, nsIClipboard return NS_OK; } - NSDictionary* pasteboardOutputDict = PasteboardDictFromTransferable(aTransferable); + NSDictionary* pasteboardOutputDict = + PasteboardDictFromTransferable(aTransferable); if (!pasteboardOutputDict) return NS_ERROR_FAILURE; unsigned int outputCount = [pasteboardOutputDict count]; @@ -100,8 +104,10 @@ nsClipboard::SetNativeClipboardData(nsITransferable* aTransferable, nsIClipboard NSPasteboard* cocoaPasteboard = GetPasteboard(aWhichClipboard); MOZ_ASSERT(cocoaPasteboard); if (aWhichClipboard == kFindClipboard) { - NSString* stringType = [UTIHelper stringFromPboardType:NSPasteboardTypeString]; - [cocoaPasteboard declareTypes:[NSArray arrayWithObject:stringType] owner:nil]; + NSString* stringType = + [UTIHelper stringFromPboardType:NSPasteboardTypeString]; + [cocoaPasteboard declareTypes:[NSArray arrayWithObject:stringType] + owner:nil]; } else { // Write everything else out to the general pasteboard. MOZ_ASSERT(aWhichClipboard == kGlobalClipboard); @@ -112,32 +118,48 @@ nsClipboard::SetNativeClipboardData(nsITransferable* aTransferable, nsIClipboard NSString* currentKey = [outputKeys objectAtIndex:i]; id currentValue = [pasteboardOutputDict valueForKey:currentKey]; if (aWhichClipboard == kFindClipboard) { - if ([currentKey isEqualToString:[UTIHelper stringFromPboardType:NSPasteboardTypeString]]) { + if ([currentKey isEqualToString:[UTIHelper stringFromPboardType: + NSPasteboardTypeString]]) { [cocoaPasteboard setString:currentValue forType:currentKey]; } } else { - if ([currentKey isEqualToString:[UTIHelper stringFromPboardType:NSPasteboardTypeString]] || - [currentKey isEqualToString:[UTIHelper stringFromPboardType:kPublicUrlPboardType]] || - [currentKey isEqualToString:[UTIHelper stringFromPboardType:kPublicUrlNamePboardType]]) { + if ([currentKey isEqualToString:[UTIHelper stringFromPboardType: + NSPasteboardTypeString]] || + [currentKey + isEqualToString:[UTIHelper + stringFromPboardType:kPublicUrlPboardType]] || + [currentKey + isEqualToString: + [UTIHelper stringFromPboardType:kPublicUrlNamePboardType]]) { [cocoaPasteboard setString:currentValue forType:currentKey]; } else if ([currentKey - isEqualToString:[UTIHelper stringFromPboardType:kUrlsWithTitlesPboardType]]) { - [cocoaPasteboard setPropertyList:[pasteboardOutputDict valueForKey:currentKey] - forType:currentKey]; + isEqualToString: + [UTIHelper + stringFromPboardType:kUrlsWithTitlesPboardType]]) { + [cocoaPasteboard + setPropertyList:[pasteboardOutputDict valueForKey:currentKey] + forType:currentKey]; } else if ([currentKey - isEqualToString:[UTIHelper stringFromPboardType:NSPasteboardTypeHTML]]) { - [cocoaPasteboard setString:(nsClipboard::WrapHtmlForSystemPasteboard(currentValue)) - forType:currentKey]; + isEqualToString:[UTIHelper stringFromPboardType: + NSPasteboardTypeHTML]]) { + [cocoaPasteboard + setString:(nsClipboard::WrapHtmlForSystemPasteboard(currentValue)) + forType:currentKey]; } else if ([currentKey - isEqualToString:[UTIHelper stringFromPboardType:kMozFileUrlsPboardType]]) { + isEqualToString:[UTIHelper stringFromPboardType: + kMozFileUrlsPboardType]]) { [cocoaPasteboard writeObjects:currentValue]; } else if ([currentKey - isEqualToString:[UTIHelper stringFromPboardType:(NSString*)kUTTypeFileURL]]) { + isEqualToString: + [UTIHelper + stringFromPboardType:(NSString*)kUTTypeFileURL]]) { [cocoaPasteboard setString:currentValue forType:currentKey]; } else if ([currentKey - isEqualToString:[UTIHelper stringFromPboardType:kPasteboardConcealedType]]) { - // It's fine to set the data to null for this field - this field is an addition - // to a value's other type and works like a flag. + isEqualToString: + [UTIHelper + stringFromPboardType:kPasteboardConcealedType]]) { + // It's fine to set the data to null for this field - this field is an + // addition to a value's other type and works like a flag. [cocoaPasteboard setData:NULL forType:currentKey]; } else { [cocoaPasteboard setData:currentValue forType:currentKey]; @@ -150,12 +172,12 @@ nsClipboard::SetNativeClipboardData(nsITransferable* aTransferable, nsIClipboard NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -nsresult nsClipboard::TransferableFromPasteboard(nsITransferable* aTransferable, - NSPasteboard* cocoaPasteboard) { +nsresult nsClipboard::TransferableFromPasteboard( + nsITransferable* aTransferable, NSPasteboard* cocoaPasteboard) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - // get flavor list that includes all acceptable flavors (including ones obtained through - // conversion) + // get flavor list that includes all acceptable flavors (including ones + // obtained through conversion) nsTArray flavors; nsresult rv = aTransferable->FlavorsTransferableCanImport(flavors); if (NS_FAILED(rv)) return NS_ERROR_FAILURE; @@ -173,8 +195,8 @@ nsresult nsClipboard::TransferableFromPasteboard(nsITransferable* aTransferable, } NSData* stringData; - bool isRTF = - [pboardType isEqualToString:[UTIHelper stringFromPboardType:NSPasteboardTypeRTF]]; + bool isRTF = [pboardType + isEqualToString:[UTIHelper stringFromPboardType:NSPasteboardTypeRTF]]; if (isRTF) { stringData = [pString dataUsingEncoding:NSASCIIStringEncoding]; } else { @@ -187,23 +209,25 @@ nsresult nsClipboard::TransferableFromPasteboard(nsITransferable* aTransferable, } [stringData getBytes:clipboardDataPtr length:dataLength]; - // The DOM only wants LF, so convert from MacOS line endings to DOM line endings. + // The DOM only wants LF, so convert from MacOS line endings to DOM line + // endings. int32_t signedDataLength = dataLength; - nsLinebreakHelpers::ConvertPlatformToDOMLinebreaks(isRTF, &clipboardDataPtr, - &signedDataLength); + nsLinebreakHelpers::ConvertPlatformToDOMLinebreaks( + isRTF, &clipboardDataPtr, &signedDataLength); dataLength = signedDataLength; // skip BOM (Byte Order Mark to distinguish little or big endian) char16_t* clipboardDataPtrNoBOM = (char16_t*)clipboardDataPtr; - if ((dataLength > 2) && - ((clipboardDataPtrNoBOM[0] == 0xFEFF) || (clipboardDataPtrNoBOM[0] == 0xFFFE))) { + if ((dataLength > 2) && ((clipboardDataPtrNoBOM[0] == 0xFEFF) || + (clipboardDataPtrNoBOM[0] == 0xFFFE))) { dataLength -= sizeof(char16_t); clipboardDataPtrNoBOM += 1; } nsCOMPtr genericDataWrapper; - nsPrimitiveHelpers::CreatePrimitiveForData(flavorStr, clipboardDataPtrNoBOM, dataLength, - getter_AddRefs(genericDataWrapper)); + nsPrimitiveHelpers::CreatePrimitiveForData( + flavorStr, clipboardDataPtrNoBOM, dataLength, + getter_AddRefs(genericDataWrapper)); aTransferable->SetTransferData(flavorStr.get(), genericDataWrapper); free(clipboardDataPtr); break; @@ -220,11 +244,14 @@ nsresult nsClipboard::TransferableFromPasteboard(nsITransferable* aTransferable, continue; } - nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem(aTransferable, flavorStr, item); + nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem(aTransferable, + flavorStr, item); } else if (flavorStr.EqualsLiteral(kCustomTypesMime)) { NSString* type = [cocoaPasteboard availableTypeFromArray: - [NSArray arrayWithObject:[UTIHelper stringFromPboardType:kMozCustomTypesPboardType]]]; + [NSArray + arrayWithObject:[UTIHelper stringFromPboardType: + kMozCustomTypesPboardType]]]; if (!type) { continue; } @@ -242,19 +269,26 @@ nsresult nsClipboard::TransferableFromPasteboard(nsITransferable* aTransferable, [pasteboardData getBytes:clipboardDataPtr length:dataLength]; nsCOMPtr genericDataWrapper; - nsPrimitiveHelpers::CreatePrimitiveForData(flavorStr, clipboardDataPtr, dataLength, - getter_AddRefs(genericDataWrapper)); + nsPrimitiveHelpers::CreatePrimitiveForData( + flavorStr, clipboardDataPtr, dataLength, + getter_AddRefs(genericDataWrapper)); aTransferable->SetTransferData(flavorStr.get(), genericDataWrapper); free(clipboardDataPtr); - } else if (flavorStr.EqualsLiteral(kJPEGImageMime) || flavorStr.EqualsLiteral(kJPGImageMime) || - flavorStr.EqualsLiteral(kPNGImageMime) || flavorStr.EqualsLiteral(kGIFImageMime)) { + } else if (flavorStr.EqualsLiteral(kJPEGImageMime) || + flavorStr.EqualsLiteral(kJPGImageMime) || + flavorStr.EqualsLiteral(kPNGImageMime) || + flavorStr.EqualsLiteral(kGIFImageMime)) { // Figure out if there's data on the pasteboard we can grab (sanity check) NSString* type = [cocoaPasteboard availableTypeFromArray: - [NSArray arrayWithObjects:[UTIHelper stringFromPboardType:(NSString*)kUTTypeFileURL], - [UTIHelper stringFromPboardType:NSPasteboardTypeTIFF], - [UTIHelper stringFromPboardType:NSPasteboardTypePNG], nil]]; + [NSArray + arrayWithObjects: + [UTIHelper + stringFromPboardType:(NSString*)kUTTypeFileURL], + [UTIHelper stringFromPboardType:NSPasteboardTypeTIFF], + [UTIHelper stringFromPboardType:NSPasteboardTypePNG], + nil]]; if (!type) continue; // Read data off the clipboard @@ -263,7 +297,8 @@ nsresult nsClipboard::TransferableFromPasteboard(nsITransferable* aTransferable, // Figure out what type we're converting to CFStringRef outputType = NULL; - if (flavorStr.EqualsLiteral(kJPEGImageMime) || flavorStr.EqualsLiteral(kJPGImageMime)) + if (flavorStr.EqualsLiteral(kJPEGImageMime) || + flavorStr.EqualsLiteral(kJPGImageMime)) outputType = CFSTR("public.jpeg"); else if (flavorStr.EqualsLiteral(kPNGImageMime)) outputType = CFSTR("public.png"); @@ -276,20 +311,23 @@ nsresult nsClipboard::TransferableFromPasteboard(nsITransferable* aTransferable, // Note that ImageIO, like all CF APIs, allows NULLs to propagate freely // and safely in most cases (like ObjC). A notable exception is CFRelease. NSDictionary* options = [NSDictionary - dictionaryWithObjectsAndKeys:(NSNumber*)kCFBooleanTrue, kCGImageSourceShouldAllowFloat, - type, kCGImageSourceTypeIdentifierHint, nil]; + dictionaryWithObjectsAndKeys:(NSNumber*)kCFBooleanTrue, + kCGImageSourceShouldAllowFloat, type, + kCGImageSourceTypeIdentifierHint, nil]; CGImageSourceRef source = nullptr; if (type == [UTIHelper stringFromPboardType:(NSString*)kUTTypeFileURL]) { NSString* urlStr = [cocoaPasteboard stringForType:type]; NSURL* url = [NSURL URLWithString:urlStr]; - source = CGImageSourceCreateWithURL((CFURLRef)url, (CFDictionaryRef)options); + source = + CGImageSourceCreateWithURL((CFURLRef)url, (CFDictionaryRef)options); } else { - source = CGImageSourceCreateWithData((CFDataRef)pasteboardData, (CFDictionaryRef)options); + source = CGImageSourceCreateWithData((CFDataRef)pasteboardData, + (CFDictionaryRef)options); } NSMutableData* encodedData = [NSMutableData data]; - CGImageDestinationRef dest = - CGImageDestinationCreateWithData((CFMutableDataRef)encodedData, outputType, 1, NULL); + CGImageDestinationRef dest = CGImageDestinationCreateWithData( + (CFMutableDataRef)encodedData, outputType, 1, NULL); CGImageDestinationAddImageFromSource(dest, source, 0, NULL); bool successfullyConverted = CGImageDestinationFinalize(dest); @@ -297,7 +335,8 @@ nsresult nsClipboard::TransferableFromPasteboard(nsITransferable* aTransferable, // Put the converted data in a form Gecko can understand nsCOMPtr byteStream; NS_NewByteInputStream(getter_AddRefs(byteStream), - mozilla::Span((const char*)[encodedData bytes], [encodedData length]), + mozilla::Span((const char*)[encodedData bytes], + [encodedData length]), NS_ASSIGNMENT_COPY); aTransferable->SetTransferData(flavorStr.get(), byteStream); @@ -321,19 +360,21 @@ nsresult nsClipboard::TransferableFromPasteboard(nsITransferable* aTransferable, } NS_IMETHODIMP -nsClipboard::GetNativeClipboardData(nsITransferable* aTransferable, int32_t aWhichClipboard) { +nsClipboard::GetNativeClipboardData(nsITransferable* aTransferable, + int32_t aWhichClipboard) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; MOZ_DIAGNOSTIC_ASSERT(aTransferable); - MOZ_DIAGNOSTIC_ASSERT(nsIClipboard::IsClipboardTypeSupported(aWhichClipboard)); + MOZ_DIAGNOSTIC_ASSERT( + nsIClipboard::IsClipboardTypeSupported(aWhichClipboard)); if (kSelectionCache == aWhichClipboard) { if (!sSelectionCache) { return NS_OK; } - // get flavor list that includes all acceptable flavors (including ones obtained through - // conversion) + // get flavor list that includes all acceptable flavors (including ones + // obtained through conversion) nsTArray flavors; nsresult rv = aTransferable->FlavorsTransferableCanImport(flavors); if (NS_FAILED(rv)) { @@ -342,7 +383,8 @@ nsClipboard::GetNativeClipboardData(nsITransferable* aTransferable, int32_t aWhi for (const auto& flavor : flavors) { nsCOMPtr dataSupports; - rv = sSelectionCache->GetTransferData(flavor.get(), getter_AddRefs(dataSupports)); + rv = sSelectionCache->GetTransferData(flavor.get(), + getter_AddRefs(dataSupports)); if (NS_SUCCEEDED(rv)) { CLIPBOARD_LOG("%s: getting %s from cache.", __FUNCTION__, flavor.get()); aTransferable->SetTransferData(flavor.get(), dataSupports); @@ -364,18 +406,22 @@ nsClipboard::GetNativeClipboardData(nsITransferable* aTransferable, int32_t aWhi } // returns true if we have *any* of the passed in flavors available for pasting -mozilla::Result nsClipboard::HasNativeClipboardDataMatchingFlavors( +mozilla::Result +nsClipboard::HasNativeClipboardDataMatchingFlavors( const nsTArray& aFlavorList, int32_t aWhichClipboard) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - MOZ_DIAGNOSTIC_ASSERT(nsIClipboard::IsClipboardTypeSupported(aWhichClipboard)); + MOZ_DIAGNOSTIC_ASSERT( + nsIClipboard::IsClipboardTypeSupported(aWhichClipboard)); if (kSelectionCache == aWhichClipboard) { nsTArray transferableFlavors; if (sSelectionCache && - NS_SUCCEEDED(sSelectionCache->FlavorsTransferableCanImport(transferableFlavors))) { + NS_SUCCEEDED(sSelectionCache->FlavorsTransferableCanImport( + transferableFlavors))) { if (CLIPBOARD_LOG_ENABLED()) { - CLIPBOARD_LOG(" SelectionCache types (nums %zu)\n", transferableFlavors.Length()); + CLIPBOARD_LOG(" SelectionCache types (nums %zu)\n", + transferableFlavors.Length()); for (const auto& transferableFlavor : transferableFlavors) { CLIPBOARD_LOG(" MIME %s", transferableFlavor.get()); } @@ -417,8 +463,8 @@ mozilla::Result nsClipboard::HasNativeClipboardDataMatchingFlavo for (auto& mimeType : aFlavorList) { NSString* pboardType = nil; if (nsClipboard::IsStringType(mimeType, &pboardType)) { - NSString* availableType = - [cocoaPasteboard availableTypeFromArray:[NSArray arrayWithObject:pboardType]]; + NSString* availableType = [cocoaPasteboard + availableTypeFromArray:[NSArray arrayWithObject:pboardType]]; if (availableType && [availableType isEqualToString:pboardType]) { CLIPBOARD_LOG(" has %s\n", mimeType.get()); return true; @@ -426,17 +472,24 @@ mozilla::Result nsClipboard::HasNativeClipboardDataMatchingFlavo } else if (mimeType.EqualsLiteral(kCustomTypesMime)) { NSString* availableType = [cocoaPasteboard availableTypeFromArray: - [NSArray arrayWithObject:[UTIHelper stringFromPboardType:kMozCustomTypesPboardType]]]; + [NSArray + arrayWithObject:[UTIHelper stringFromPboardType: + kMozCustomTypesPboardType]]]; if (availableType) { CLIPBOARD_LOG(" has %s\n", mimeType.get()); return true; } - } else if (mimeType.EqualsLiteral(kJPEGImageMime) || mimeType.EqualsLiteral(kJPGImageMime) || - mimeType.EqualsLiteral(kPNGImageMime) || mimeType.EqualsLiteral(kGIFImageMime)) { + } else if (mimeType.EqualsLiteral(kJPEGImageMime) || + mimeType.EqualsLiteral(kJPGImageMime) || + mimeType.EqualsLiteral(kPNGImageMime) || + mimeType.EqualsLiteral(kGIFImageMime)) { NSString* availableType = [cocoaPasteboard availableTypeFromArray: - [NSArray arrayWithObjects:[UTIHelper stringFromPboardType:NSPasteboardTypeTIFF], - [UTIHelper stringFromPboardType:NSPasteboardTypePNG], nil]]; + [NSArray + arrayWithObjects: + [UTIHelper stringFromPboardType:NSPasteboardTypeTIFF], + [UTIHelper stringFromPboardType:NSPasteboardTypePNG], + nil]]; if (availableType) { CLIPBOARD_LOG(" has %s\n", mimeType.get()); return true; @@ -449,9 +502,11 @@ mozilla::Result nsClipboard::HasNativeClipboardDataMatchingFlavo if (NSPasteboardItem* item = [items objectAtIndex:0]) { if (NSString *availableType = [item availableTypeFromArray: - [NSArray arrayWithObjects:[UTIHelper - stringFromPboardType:(NSString*)kUTTypeFileURL], - nil]]) { + [NSArray + arrayWithObjects:[UTIHelper + stringFromPboardType: + (NSString*)kUTTypeFileURL], + nil]]) { CLIPBOARD_LOG(" has %s\n", mimeType.get()); return true; } @@ -481,10 +536,10 @@ mozilla::Maybe nsClipboard::FindIndexOfImageFlavor( return mozilla::Nothing(); } -// This function converts anything that other applications might understand into the system format -// and puts it into a dictionary which it returns. -// static -NSDictionary* nsClipboard::PasteboardDictFromTransferable(nsITransferable* aTransferable) { +// This function converts anything that other applications might understand into +// the system format and puts it into a dictionary which it returns. static +NSDictionary* nsClipboard::PasteboardDictFromTransferable( + nsITransferable* aTransferable) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; if (!aTransferable) { @@ -499,29 +554,33 @@ NSDictionary* nsClipboard::PasteboardDictFromTransferable(nsITransferable* aTran return nil; } - const mozilla::Maybe imageFlavorIndex = nsClipboard::FindIndexOfImageFlavor(flavors); + const mozilla::Maybe imageFlavorIndex = + nsClipboard::FindIndexOfImageFlavor(flavors); if (imageFlavorIndex) { - // When right-clicking and "Copy Image" is clicked on macOS, some apps expect the - // first flavor to be the image flavor. See bug 1689992. For other apps, the - // order shouldn't matter. + // When right-clicking and "Copy Image" is clicked on macOS, some apps + // expect the first flavor to be the image flavor. See bug 1689992. For + // other apps, the order shouldn't matter. std::swap(*flavors.begin(), flavors[*imageFlavorIndex]); } for (uint32_t i = 0; i < flavors.Length(); i++) { nsCString& flavorStr = flavors[i]; - CLIPBOARD_LOG("writing out clipboard data of type %s (%d)\n", flavorStr.get(), i); + CLIPBOARD_LOG("writing out clipboard data of type %s (%d)\n", + flavorStr.get(), i); NSString* pboardType = nil; if (nsClipboard::IsStringType(flavorStr, &pboardType)) { nsCOMPtr genericDataWrapper; - rv = aTransferable->GetTransferData(flavorStr.get(), getter_AddRefs(genericDataWrapper)); + rv = aTransferable->GetTransferData(flavorStr.get(), + getter_AddRefs(genericDataWrapper)); if (NS_FAILED(rv)) { continue; } nsAutoString data; - if (nsCOMPtr text = do_QueryInterface(genericDataWrapper)) { + if (nsCOMPtr text = + do_QueryInterface(genericDataWrapper)) { text->GetData(data); } @@ -540,26 +599,32 @@ NSDictionary* nsClipboard::PasteboardDictFromTransferable(nsITransferable* aTran } if (aTransferable->GetIsPrivateData()) { - // In the case of password strings, we want to include the key for concealed type. - // These will be flagged as private data. - [pasteboardOutputDict setObject:nativeString - forKey:[UTIHelper stringFromPboardType:kPasteboardConcealedType]]; + // In the case of password strings, we want to include the key for + // concealed type. These will be flagged as private data. + [pasteboardOutputDict + setObject:nativeString + forKey:[UTIHelper + stringFromPboardType:kPasteboardConcealedType]]; } } else if (flavorStr.EqualsLiteral(kCustomTypesMime)) { nsCOMPtr genericDataWrapper; - rv = aTransferable->GetTransferData(flavorStr.get(), getter_AddRefs(genericDataWrapper)); + rv = aTransferable->GetTransferData(flavorStr.get(), + getter_AddRefs(genericDataWrapper)); if (NS_FAILED(rv)) { continue; } nsAutoCString data; - if (nsCOMPtr text = do_QueryInterface(genericDataWrapper)) { + if (nsCOMPtr text = + do_QueryInterface(genericDataWrapper)) { text->GetData(data); } if (!data.IsEmpty()) { - NSData* nativeData = [NSData dataWithBytes:data.get() length:data.Length()]; - NSString* customType = [UTIHelper stringFromPboardType:kMozCustomTypesPboardType]; + NSData* nativeData = [NSData dataWithBytes:data.get() + length:data.Length()]; + NSString* customType = + [UTIHelper stringFromPboardType:kMozCustomTypesPboardType]; if (!nativeData) { continue; } @@ -567,7 +632,8 @@ NSDictionary* nsClipboard::PasteboardDictFromTransferable(nsITransferable* aTran } } else if (nsClipboard::IsImageType(flavorStr)) { nsCOMPtr transferSupports; - rv = aTransferable->GetTransferData(flavorStr.get(), getter_AddRefs(transferSupports)); + rv = aTransferable->GetTransferData(flavorStr.get(), + getter_AddRefs(transferSupports)); if (NS_FAILED(rv)) { continue; } @@ -578,9 +644,9 @@ NSDictionary* nsClipboard::PasteboardDictFromTransferable(nsITransferable* aTran continue; } - RefPtr surface = - image->GetFrame(imgIContainer::FRAME_CURRENT, - imgIContainer::FLAG_SYNC_DECODE | imgIContainer::FLAG_ASYNC_NOTIFY); + RefPtr surface = image->GetFrame( + imgIContainer::FRAME_CURRENT, + imgIContainer::FLAG_SYNC_DECODE | imgIContainer::FLAG_ASYNC_NOTIFY); if (!surface) { continue; } @@ -592,8 +658,8 @@ NSDictionary* nsClipboard::PasteboardDictFromTransferable(nsITransferable* aTran // Convert the CGImageRef to TIFF data. CFMutableDataRef tiffData = CFDataCreateMutable(kCFAllocatorDefault, 0); - CGImageDestinationRef destRef = - CGImageDestinationCreateWithData(tiffData, CFSTR("public.tiff"), 1, NULL); + CGImageDestinationRef destRef = CGImageDestinationCreateWithData( + tiffData, CFSTR("public.tiff"), 1, NULL); CGImageDestinationAddImage(destRef, imageRef, NULL); bool successfullyConverted = CGImageDestinationFinalize(destRef); @@ -609,12 +675,14 @@ NSDictionary* nsClipboard::PasteboardDictFromTransferable(nsITransferable* aTran continue; } - NSString* tiffType = [UTIHelper stringFromPboardType:NSPasteboardTypeTIFF]; + NSString* tiffType = + [UTIHelper stringFromPboardType:NSPasteboardTypeTIFF]; [pasteboardOutputDict setObject:(NSMutableData*)tiffData forKey:tiffType]; CFRelease(tiffData); } else if (flavorStr.EqualsLiteral(kFileMime)) { nsCOMPtr genericFile; - rv = aTransferable->GetTransferData(flavorStr.get(), getter_AddRefs(genericFile)); + rv = aTransferable->GetTransferData(flavorStr.get(), + getter_AddRefs(genericFile)); if (NS_FAILED(rv)) { continue; } @@ -635,18 +703,22 @@ NSDictionary* nsClipboard::PasteboardDictFromTransferable(nsITransferable* aTran if (!url || ![url absoluteString]) { continue; } - NSString* fileUTType = [UTIHelper stringFromPboardType:(NSString*)kUTTypeFileURL]; + NSString* fileUTType = + [UTIHelper stringFromPboardType:(NSString*)kUTTypeFileURL]; [pasteboardOutputDict setObject:[url absoluteString] forKey:fileUTType]; } else if (flavorStr.EqualsLiteral(kFilePromiseMime)) { - NSString* urlPromise = - [UTIHelper stringFromPboardType:(NSString*)kPasteboardTypeFileURLPromise]; - NSString* urlPromiseContent = - [UTIHelper stringFromPboardType:(NSString*)kPasteboardTypeFilePromiseContent]; - [pasteboardOutputDict setObject:[NSArray arrayWithObject:@""] forKey:urlPromise]; - [pasteboardOutputDict setObject:[NSArray arrayWithObject:@""] forKey:urlPromiseContent]; + NSString* urlPromise = [UTIHelper + stringFromPboardType:(NSString*)kPasteboardTypeFileURLPromise]; + NSString* urlPromiseContent = [UTIHelper + stringFromPboardType:(NSString*)kPasteboardTypeFilePromiseContent]; + [pasteboardOutputDict setObject:[NSArray arrayWithObject:@""] + forKey:urlPromise]; + [pasteboardOutputDict setObject:[NSArray arrayWithObject:@""] + forKey:urlPromiseContent]; } else if (flavorStr.EqualsLiteral(kURLMime)) { nsCOMPtr genericURL; - rv = aTransferable->GetTransferData(flavorStr.get(), getter_AddRefs(genericURL)); + rv = aTransferable->GetTransferData(flavorStr.get(), + getter_AddRefs(genericURL)); nsCOMPtr urlObject(do_QueryInterface(genericURL)); nsAutoString url; @@ -662,10 +734,12 @@ NSDictionary* nsClipboard::PasteboardDictFromTransferable(nsITransferable* aTran nsAutoString urlTitle; urlObject->GetData(urlTitle); - urlTitle.Mid(urlTitle, newlinePos + 1, urlTitle.Length() - (newlinePos + 1)); + urlTitle.Mid(urlTitle, newlinePos + 1, + urlTitle.Length() - (newlinePos + 1)); nativeTitle = - [NSString stringWithCharacters:reinterpret_cast(urlTitle.get()) + [NSString stringWithCharacters:reinterpret_cast( + urlTitle.get()) length:urlTitle.Length()]; } // The Finder doesn't like getting random binary data aka @@ -673,24 +747,29 @@ NSDictionary* nsClipboard::PasteboardDictFromTransferable(nsITransferable* aTran // ASCII. nsAutoCString utf8Data = NS_ConvertUTF16toUTF8(url.get(), url.Length()); nsAutoCString escData; - NS_EscapeURL(utf8Data.get(), utf8Data.Length(), esc_OnlyNonASCII | esc_AlwaysCopy, escData); + NS_EscapeURL(utf8Data.get(), utf8Data.Length(), + esc_OnlyNonASCII | esc_AlwaysCopy, escData); NSString* nativeURL = [NSString stringWithUTF8String:escData.get()]; - NSString* publicUrl = [UTIHelper stringFromPboardType:kPublicUrlPboardType]; + NSString* publicUrl = + [UTIHelper stringFromPboardType:kPublicUrlPboardType]; if (!nativeURL) { continue; } [pasteboardOutputDict setObject:nativeURL forKey:publicUrl]; if (nativeTitle) { NSArray* urlsAndTitles = @[ @[ nativeURL ], @[ nativeTitle ] ]; - NSString* urlName = [UTIHelper stringFromPboardType:kPublicUrlNamePboardType]; - NSString* urlsWithTitles = [UTIHelper stringFromPboardType:kUrlsWithTitlesPboardType]; + NSString* urlName = + [UTIHelper stringFromPboardType:kPublicUrlNamePboardType]; + NSString* urlsWithTitles = + [UTIHelper stringFromPboardType:kUrlsWithTitlesPboardType]; [pasteboardOutputDict setObject:nativeTitle forKey:urlName]; [pasteboardOutputDict setObject:urlsAndTitles forKey:urlsWithTitles]; } } - // If it wasn't a type that we recognize as exportable we don't put it on the system - // clipboard. We'll just access it from our cached transferable when we need it. + // If it wasn't a type that we recognize as exportable we don't put it on + // the system clipboard. We'll just access it from our cached transferable + // when we need it. } return pasteboardOutputDict; @@ -698,7 +777,8 @@ NSDictionary* nsClipboard::PasteboardDictFromTransferable(nsITransferable* aTran NS_OBJC_END_TRY_BLOCK_RETURN(nil); } -bool nsClipboard::IsStringType(const nsCString& aMIMEType, NSString** aPboardType) { +bool nsClipboard::IsStringType(const nsCString& aMIMEType, + NSString** aPboardType) { if (aMIMEType.EqualsLiteral(kTextMime)) { *aPboardType = [UTIHelper stringFromPboardType:NSPasteboardTypeString]; return true; @@ -715,29 +795,33 @@ bool nsClipboard::IsStringType(const nsCString& aMIMEType, NSString** aPboardTyp // static bool nsClipboard::IsImageType(const nsACString& aMIMEType) { - return aMIMEType.EqualsLiteral(kPNGImageMime) || aMIMEType.EqualsLiteral(kJPEGImageMime) || - aMIMEType.EqualsLiteral(kJPGImageMime) || aMIMEType.EqualsLiteral(kGIFImageMime) || + return aMIMEType.EqualsLiteral(kPNGImageMime) || + aMIMEType.EqualsLiteral(kJPEGImageMime) || + aMIMEType.EqualsLiteral(kJPGImageMime) || + aMIMEType.EqualsLiteral(kGIFImageMime) || aMIMEType.EqualsLiteral(kNativeImageMime); } NSString* nsClipboard::WrapHtmlForSystemPasteboard(NSString* aString) { - NSString* wrapped = [NSString - stringWithFormat:@"" - "" - "" - "" - "" - "%@" - "" - "", - aString]; + NSString* wrapped = + [NSString stringWithFormat:@"" + "" + "" + "" + "" + "%@" + "" + "", + aString]; return wrapped; } nsresult nsClipboard::EmptyNativeClipboardData(int32_t aWhichClipboard) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - MOZ_DIAGNOSTIC_ASSERT(nsIClipboard::IsClipboardTypeSupported(aWhichClipboard)); + MOZ_DIAGNOSTIC_ASSERT( + nsIClipboard::IsClipboardTypeSupported(aWhichClipboard)); if (kSelectionCache == aWhichClipboard) { ClearSelectionCache(); @@ -753,11 +837,12 @@ nsresult nsClipboard::EmptyNativeClipboardData(int32_t aWhichClipboard) { NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -mozilla::Result nsClipboard::GetNativeClipboardSequenceNumber( - int32_t aWhichClipboard) { +mozilla::Result +nsClipboard::GetNativeClipboardSequenceNumber(int32_t aWhichClipboard) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - MOZ_DIAGNOSTIC_ASSERT(nsIClipboard::IsClipboardTypeSupported(aWhichClipboard)); + MOZ_DIAGNOSTIC_ASSERT( + nsIClipboard::IsClipboardTypeSupported(aWhichClipboard)); if (kSelectionCache == aWhichClipboard) { return sSelectionCacheChangeCount; diff --git a/widget/cocoa/nsCocoaFeatures.mm b/widget/cocoa/nsCocoaFeatures.mm index cf68755078f9..35da53771f35 100644 --- a/widget/cocoa/nsCocoaFeatures.mm +++ b/widget/cocoa/nsCocoaFeatures.mm @@ -38,7 +38,8 @@ /*static*/ int32_t nsCocoaFeatures::mOSVersion = 0; // This should not be called with unchecked aMajor, which should be >= 10. -inline int32_t AssembleVersion(int32_t aMajor, int32_t aMinor, int32_t aBugFix) { +inline int32_t AssembleVersion(int32_t aMajor, int32_t aMinor, + int32_t aBugFix) { MOZ_ASSERT(aMajor >= 10); return (aMajor << 16) + (aMinor << 8) + aBugFix; } @@ -65,11 +66,13 @@ static int intAtStringIndex(NSArray* array, int index) { void nsCocoaFeatures::GetSystemVersion(int& major, int& minor, int& bugfix) { major = minor = bugfix = 0; - NSString* versionString = [[NSDictionary - dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"] - objectForKey:@"ProductVersion"]; + NSString* versionString = + [[NSDictionary dictionaryWithContentsOfFile: + @"/System/Library/CoreServices/SystemVersion.plist"] + objectForKey:@"ProductVersion"]; if (!versionString) { - NS_ERROR("Couldn't read /System/Library/CoreServices/SystemVersion.plist to determine macOS " + NS_ERROR("Couldn't read /System/Library/CoreServices/SystemVersion.plist " + "to determine macOS " "version."); return; } @@ -86,7 +89,8 @@ void nsCocoaFeatures::GetSystemVersion(int& major, int& minor, int& bugfix) { } } -int32_t nsCocoaFeatures::GetVersion(int32_t aMajor, int32_t aMinor, int32_t aBugFix) { +int32_t nsCocoaFeatures::GetVersion(int32_t aMajor, int32_t aMinor, + int32_t aBugFix) { int32_t macOSVersion; if (aMajor < 10) { aMajor = 10; @@ -148,7 +152,8 @@ int32_t nsCocoaFeatures::GetVersion(int32_t aMajor, int32_t aMinor, int32_t aBug } /* static */ bool nsCocoaFeatures::OnSierraExactly() { - return (macOSVersion() >= MACOS_VERSION_10_12_HEX) && (macOSVersion() < MACOS_VERSION_10_13_HEX); + return (macOSVersion() >= MACOS_VERSION_10_12_HEX) && + (macOSVersion() < MACOS_VERSION_10_13_HEX); } /* Version of OnSierraExactly as global function callable from cairo & skia */ @@ -195,7 +200,8 @@ bool Gecko_OnSierraExactly() { return nsCocoaFeatures::OnSierraExactly(); } return (macOSVersion() >= MACOS_VERSION_13_0_HEX); } -/* static */ bool nsCocoaFeatures::IsAtLeastVersion(int32_t aMajor, int32_t aMinor, +/* static */ bool nsCocoaFeatures::IsAtLeastVersion(int32_t aMajor, + int32_t aMinor, int32_t aBugFix) { return macOSVersion() >= GetVersion(aMajor, aMinor, aBugFix); } diff --git a/widget/cocoa/nsCocoaUtils.mm b/widget/cocoa/nsCocoaUtils.mm index db1bc2f83cee..161351c21b95 100644 --- a/widget/cocoa/nsCocoaUtils.mm +++ b/widget/cocoa/nsCocoaUtils.mm @@ -97,8 +97,10 @@ NSString* const kMozFileUrlsPboardType = @"org.mozilla.file-urls"; [aType isEqualToString:(NSString*)kUTTypeFileURL] || [aType isEqualToString:NSStringPboardType] || [aType isEqualToString:NSPasteboardTypeString] || - [aType isEqualToString:NSPasteboardTypeHTML] || [aType isEqualToString:NSPasteboardTypeRTF] || - [aType isEqualToString:NSPasteboardTypeTIFF] || [aType isEqualToString:NSPasteboardTypePNG]) { + [aType isEqualToString:NSPasteboardTypeHTML] || + [aType isEqualToString:NSPasteboardTypeRTF] || + [aType isEqualToString:NSPasteboardTypeTIFF] || + [aType isEqualToString:NSPasteboardTypePNG]) { return [NSString stringWithString:aType]; } NSString* dynamicType = (NSString*)UTTypeCreatePreferredIdentifierForTag( @@ -123,24 +125,28 @@ static float MenuBarScreenHeight() { NS_OBJC_END_TRY_BLOCK_RETURN(0.0); } -float nsCocoaUtils::FlippedScreenY(float y) { return MenuBarScreenHeight() - y; } +float nsCocoaUtils::FlippedScreenY(float y) { + return MenuBarScreenHeight() - y; +} NSRect nsCocoaUtils::GeckoRectToCocoaRect(const DesktopIntRect& geckoRect) { // We only need to change the Y coordinate by starting with the primary screen // height and subtracting the gecko Y coordinate of the bottom of the rect. - return NSMakeRect(geckoRect.x, MenuBarScreenHeight() - geckoRect.YMost(), geckoRect.width, - geckoRect.height); + return NSMakeRect(geckoRect.x, MenuBarScreenHeight() - geckoRect.YMost(), + geckoRect.width, geckoRect.height); } -NSPoint nsCocoaUtils::GeckoPointToCocoaPoint(const mozilla::DesktopPoint& aPoint) { +NSPoint nsCocoaUtils::GeckoPointToCocoaPoint( + const mozilla::DesktopPoint& aPoint) { return NSMakePoint(aPoint.x, MenuBarScreenHeight() - aPoint.y); } -NSRect nsCocoaUtils::GeckoRectToCocoaRectDevPix(const LayoutDeviceIntRect& aGeckoRect, - CGFloat aBackingScale) { +NSRect nsCocoaUtils::GeckoRectToCocoaRectDevPix( + const LayoutDeviceIntRect& aGeckoRect, CGFloat aBackingScale) { return NSMakeRect(aGeckoRect.x / aBackingScale, MenuBarScreenHeight() - aGeckoRect.YMost() / aBackingScale, - aGeckoRect.width / aBackingScale, aGeckoRect.height / aBackingScale); + aGeckoRect.width / aBackingScale, + aGeckoRect.height / aBackingScale); } DesktopIntRect nsCocoaUtils::CocoaRectToGeckoRect(const NSRect& cocoaRect) { @@ -149,20 +155,26 @@ DesktopIntRect nsCocoaUtils::CocoaRectToGeckoRect(const NSRect& cocoaRect) { // cocoa rect. DesktopIntRect rect; rect.x = NSToIntRound(cocoaRect.origin.x); - rect.y = NSToIntRound(FlippedScreenY(cocoaRect.origin.y + cocoaRect.size.height)); + rect.y = + NSToIntRound(FlippedScreenY(cocoaRect.origin.y + cocoaRect.size.height)); rect.width = NSToIntRound(cocoaRect.origin.x + cocoaRect.size.width) - rect.x; rect.height = NSToIntRound(FlippedScreenY(cocoaRect.origin.y)) - rect.y; return rect; } -LayoutDeviceIntRect nsCocoaUtils::CocoaRectToGeckoRectDevPix(const NSRect& aCocoaRect, - CGFloat aBackingScale) { +LayoutDeviceIntRect nsCocoaUtils::CocoaRectToGeckoRectDevPix( + const NSRect& aCocoaRect, CGFloat aBackingScale) { LayoutDeviceIntRect rect; rect.x = NSToIntRound(aCocoaRect.origin.x * aBackingScale); - rect.y = - NSToIntRound(FlippedScreenY(aCocoaRect.origin.y + aCocoaRect.size.height) * aBackingScale); - rect.width = NSToIntRound((aCocoaRect.origin.x + aCocoaRect.size.width) * aBackingScale) - rect.x; - rect.height = NSToIntRound(FlippedScreenY(aCocoaRect.origin.y) * aBackingScale) - rect.y; + rect.y = NSToIntRound( + FlippedScreenY(aCocoaRect.origin.y + aCocoaRect.size.height) * + aBackingScale); + rect.width = NSToIntRound((aCocoaRect.origin.x + aCocoaRect.size.width) * + aBackingScale) - + rect.x; + rect.height = + NSToIntRound(FlippedScreenY(aCocoaRect.origin.y) * aBackingScale) - + rect.y; return rect; } @@ -170,13 +182,16 @@ NSPoint nsCocoaUtils::ScreenLocationForEvent(NSEvent* anEvent) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; // Don't trust mouse locations of mouse move events, see bug 443178. - if (!anEvent || [anEvent type] == NSEventTypeMouseMoved) return [NSEvent mouseLocation]; + if (!anEvent || [anEvent type] == NSEventTypeMouseMoved) + return [NSEvent mouseLocation]; // Pin momentum scroll events to the location of the last user-controlled // scroll event. - if (IsMomentumScrollEvent(anEvent)) return ChildViewMouseTracker::sLastScrollEventScreenLocation; + if (IsMomentumScrollEvent(anEvent)) + return ChildViewMouseTracker::sLastScrollEventScreenLocation; - return nsCocoaUtils::ConvertPointToScreen([anEvent window], [anEvent locationInWindow]); + return nsCocoaUtils::ConvertPointToScreen([anEvent window], + [anEvent locationInWindow]); NS_OBJC_END_TRY_BLOCK_RETURN(NSMakePoint(0.0, 0.0)); } @@ -189,20 +204,24 @@ BOOL nsCocoaUtils::IsEventOverWindow(NSEvent* anEvent, NSWindow* aWindow) { NS_OBJC_END_TRY_BLOCK_RETURN(NO); } -NSPoint nsCocoaUtils::EventLocationForWindow(NSEvent* anEvent, NSWindow* aWindow) { +NSPoint nsCocoaUtils::EventLocationForWindow(NSEvent* anEvent, + NSWindow* aWindow) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - return nsCocoaUtils::ConvertPointFromScreen(aWindow, ScreenLocationForEvent(anEvent)); + return nsCocoaUtils::ConvertPointFromScreen(aWindow, + ScreenLocationForEvent(anEvent)); NS_OBJC_END_TRY_BLOCK_RETURN(NSMakePoint(0.0, 0.0)); } BOOL nsCocoaUtils::IsMomentumScrollEvent(NSEvent* aEvent) { - return [aEvent type] == NSEventTypeScrollWheel && [aEvent momentumPhase] != NSEventPhaseNone; + return [aEvent type] == NSEventTypeScrollWheel && + [aEvent momentumPhase] != NSEventPhaseNone; } BOOL nsCocoaUtils::EventHasPhaseInformation(NSEvent* aEvent) { - return [aEvent phase] != NSEventPhaseNone || [aEvent momentumPhase] != NSEventPhaseNone; + return [aEvent phase] != NSEventPhaseNone || + [aEvent momentumPhase] != NSEventPhaseNone; } void nsCocoaUtils::HideOSChromeOnScreen(bool aShouldHide) { @@ -217,7 +236,8 @@ void nsCocoaUtils::HideOSChromeOnScreen(bool aShouldHide) { NSApplicationPresentationOptions options = sHiddenCount <= 0 ? NSApplicationPresentationDefault - : NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar; + : NSApplicationPresentationHideDock | + NSApplicationPresentationHideMenuBar; [NSApp setPresentationOptions:options]; NS_OBJC_END_TRY_IGNORE_BLOCK; @@ -225,9 +245,11 @@ void nsCocoaUtils::HideOSChromeOnScreen(bool aShouldHide) { #define NS_APPSHELLSERVICE_CONTRACTID "@mozilla.org/appshell/appShellService;1" nsIWidget* nsCocoaUtils::GetHiddenWindowWidget() { - nsCOMPtr appShell(do_GetService(NS_APPSHELLSERVICE_CONTRACTID)); + nsCOMPtr appShell( + do_GetService(NS_APPSHELLSERVICE_CONTRACTID)); if (!appShell) { - NS_WARNING("Couldn't get AppShellService in order to get hidden window ref"); + NS_WARNING( + "Couldn't get AppShellService in order to get hidden window ref"); return nullptr; } @@ -246,7 +268,8 @@ nsIWidget* nsCocoaUtils::GetHiddenWindowWidget() { } nsCOMPtr hiddenWindowWidget; - if (NS_FAILED(baseHiddenWindow->GetMainWidget(getter_AddRefs(hiddenWindowWidget)))) { + if (NS_FAILED(baseHiddenWindow->GetMainWidget( + getter_AddRefs(hiddenWindowWidget)))) { NS_WARNING("Couldn't get nsIWidget from hidden window (nsIBaseWindow)"); return nullptr; } @@ -264,7 +287,8 @@ BOOL nsCocoaUtils::WasLaunchedAtLogin() { if (::GetProcessInformation(&processSerialNumber, &processInfoRec) == noErr) { ProcessInfoRec parentProcessInfo = {}; parentProcessInfo.processInfoLength = sizeof(parentProcessInfo); - if (::GetProcessInformation(&processInfoRec.processLauncher, &parentProcessInfo) == noErr) { + if (::GetProcessInformation(&processInfoRec.processLauncher, + &parentProcessInfo) == noErr) { return parentProcessInfo.processSignature == 'lgnw'; } } @@ -280,8 +304,8 @@ BOOL nsCocoaUtils::ShouldRestoreStateDueToLaunchAtLoginImpl() { CFStringRef lgnwPlistName = CFSTR("com.apple.loginwindow"); CFStringRef saveStateKey = CFSTR("TALLogoutSavesState"); - CFPropertyListRef lgnwPlist = - (CFPropertyListRef)(::CFPreferencesCopyAppValue(saveStateKey, lgnwPlistName)); + CFPropertyListRef lgnwPlist = (CFPropertyListRef)(::CFPreferencesCopyAppValue( + saveStateKey, lgnwPlistName)); // The .plist doesn't exist unless the user changed the "Reopen windows..." // preference. If it doesn't exist, restore by default (as this is the macOS // default). @@ -299,30 +323,34 @@ BOOL nsCocoaUtils::ShouldRestoreStateDueToLaunchAtLoginImpl() { BOOL nsCocoaUtils::ShouldRestoreStateDueToLaunchAtLogin() { BOOL shouldRestore = ShouldRestoreStateDueToLaunchAtLoginImpl(); - Telemetry::ScalarSet(Telemetry::ScalarID::STARTUP_IS_RESTORED_BY_MACOS, !!shouldRestore); + Telemetry::ScalarSet(Telemetry::ScalarID::STARTUP_IS_RESTORED_BY_MACOS, + !!shouldRestore); return shouldRestore; } void nsCocoaUtils::PrepareForNativeAppModalDialog() { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - // Don't do anything if this is embedding. We'll assume that if there is no hidden - // window we shouldn't do anything, and that should cover the embedding case. + // Don't do anything if this is embedding. We'll assume that if there is no + // hidden window we shouldn't do anything, and that should cover the embedding + // case. nsMenuBarX* hiddenWindowMenuBar = nsMenuUtilsX::GetHiddenWindowMenuBar(); if (!hiddenWindowMenuBar) return; - // First put up the hidden window menu bar so that app menu event handling is correct. + // First put up the hidden window menu bar so that app menu event handling is + // correct. hiddenWindowMenuBar->Paint(); NSMenu* mainMenu = [NSApp mainMenu]; - NS_ASSERTION([mainMenu numberOfItems] > 0, - "Main menu does not have any items, something is terribly wrong!"); + NS_ASSERTION( + [mainMenu numberOfItems] > 0, + "Main menu does not have any items, something is terribly wrong!"); // Create new menu bar for use with modal dialog NSMenu* newMenuBar = [[NSMenu alloc] initWithTitle:@""]; - // Swap in our app menu. Note that the event target is whatever window is up when - // the app modal dialog goes up. + // Swap in our app menu. Note that the event target is whatever window is up + // when the app modal dialog goes up. NSMenuItem* firstMenuItem = [[mainMenu itemAtIndex:0] retain]; [mainMenu removeItemAtIndex:0]; [newMenuBar insertItem:firstMenuItem atIndex:0]; @@ -341,8 +369,9 @@ void nsCocoaUtils::PrepareForNativeAppModalDialog() { void nsCocoaUtils::CleanUpAfterNativeAppModalDialog() { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - // Don't do anything if this is embedding. We'll assume that if there is no hidden - // window we shouldn't do anything, and that should cover the embedding case. + // Don't do anything if this is embedding. We'll assume that if there is no + // hidden window we shouldn't do anything, and that should cover the embedding + // case. nsMenuBarX* hiddenWindowMenuBar = nsMenuUtilsX::GetHiddenWindowMenuBar(); if (!hiddenWindowMenuBar) return; @@ -355,7 +384,8 @@ void nsCocoaUtils::CleanUpAfterNativeAppModalDialog() { NS_OBJC_END_TRY_IGNORE_BLOCK; } -static void data_ss_release_callback(void* aDataSourceSurface, const void* data, size_t size) { +static void data_ss_release_callback(void* aDataSourceSurface, const void* data, + size_t size) { if (aDataSourceSurface) { static_cast(aDataSourceSurface)->Unmap(); static_cast(aDataSourceSurface)->Release(); @@ -369,7 +399,8 @@ static bool ComputeIsEntirelyBlack(const DataSourceSurface::MappedSurface& aMap, size_t rowStart = y * aMap.mStride; for (int32_t x = 0; x < aSize.width; x++) { size_t index = rowStart + x * 4; - if (aMap.mData[index + 0] != 0 || aMap.mData[index + 1] != 0 || aMap.mData[index + 2] != 0) { + if (aMap.mData[index + 0] != 0 || aMap.mData[index + 1] != 0 || + aMap.mData[index + 2] != 0) { return false; } } @@ -377,7 +408,8 @@ static bool ComputeIsEntirelyBlack(const DataSourceSurface::MappedSurface& aMap, return true; } -nsresult nsCocoaUtils::CreateCGImageFromSurface(SourceSurface* aSurface, CGImageRef* aResult, +nsresult nsCocoaUtils::CreateCGImageFromSurface(SourceSurface* aSurface, + CGImageRef* aResult, bool* aIsEntirelyBlack) { RefPtr dataSurface; @@ -386,8 +418,8 @@ nsresult nsCocoaUtils::CreateCGImageFromSurface(SourceSurface* aSurface, CGImage } else { // CGImageCreate only supports 16- and 32-bit bit-depth // Convert format to SurfaceFormat::B8G8R8A8 - dataSurface = - gfxUtils::CopySurfaceToDataSourceSurfaceWithFormat(aSurface, SurfaceFormat::B8G8R8A8); + dataSurface = gfxUtils::CopySurfaceToDataSourceSurfaceWithFormat( + aSurface, SurfaceFormat::B8G8R8A8); } NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE); @@ -412,17 +444,21 @@ nsresult nsCocoaUtils::CreateCGImageFromSurface(SourceSurface* aSurface, CGImage // the alpha ordering and endianness of the machine so we don't have to // touch the bits ourselves. CGDataProviderRef dataProvider = ::CGDataProviderCreateWithData( - dataSurface.forget().take(), map.mData, map.mStride * height, data_ss_release_callback); - CGColorSpaceRef colorSpace = ::CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); - *aResult = ::CGImageCreate(width, height, 8, 32, map.mStride, colorSpace, - kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst, - dataProvider, NULL, 0, kCGRenderingIntentDefault); + dataSurface.forget().take(), map.mData, map.mStride * height, + data_ss_release_callback); + CGColorSpaceRef colorSpace = + ::CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); + *aResult = ::CGImageCreate( + width, height, 8, 32, map.mStride, colorSpace, + kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst, dataProvider, + NULL, 0, kCGRenderingIntentDefault); ::CGColorSpaceRelease(colorSpace); ::CGDataProviderRelease(dataProvider); return *aResult ? NS_OK : NS_ERROR_FAILURE; } -nsresult nsCocoaUtils::CreateNSImageFromCGImage(CGImageRef aInputImage, NSImage** aResult) { +nsresult nsCocoaUtils::CreateNSImageFromCGImage(CGImageRef aInputImage, + NSImage** aResult) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; // Be very careful when creating the NSImage that the backing NSImageRep is @@ -444,20 +480,21 @@ nsresult nsCocoaUtils::CreateNSImageFromCGImage(CGImageRef aInputImage, NSImage* int32_t height = ::CGImageGetHeight(aInputImage); NSRect imageRect = ::NSMakeRect(0.0, 0.0, width, height); - NSBitmapImageRep* offscreenRep = - [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL - pixelsWide:width - pixelsHigh:height - bitsPerSample:8 - samplesPerPixel:4 - hasAlpha:YES - isPlanar:NO - colorSpaceName:NSDeviceRGBColorSpace - bitmapFormat:NSAlphaFirstBitmapFormat - bytesPerRow:0 - bitsPerPixel:0]; + NSBitmapImageRep* offscreenRep = [[NSBitmapImageRep alloc] + initWithBitmapDataPlanes:NULL + pixelsWide:width + pixelsHigh:height + bitsPerSample:8 + samplesPerPixel:4 + hasAlpha:YES + isPlanar:NO + colorSpaceName:NSDeviceRGBColorSpace + bitmapFormat:NSAlphaFirstBitmapFormat + bytesPerRow:0 + bitsPerPixel:0]; - NSGraphicsContext* context = [NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep]; + NSGraphicsContext* context = + [NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep]; [NSGraphicsContext saveGraphicsState]; [NSGraphicsContext setCurrentContext:context]; @@ -475,11 +512,10 @@ nsresult nsCocoaUtils::CreateNSImageFromCGImage(CGImageRef aInputImage, NSImage* NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -nsresult nsCocoaUtils::CreateNSImageFromImageContainer(imgIContainer* aImage, uint32_t aWhichFrame, - const nsPresContext* aPresContext, - const ComputedStyle* aComputedStyle, - NSImage** aResult, CGFloat scaleFactor, - bool* aIsEntirelyBlack) { +nsresult nsCocoaUtils::CreateNSImageFromImageContainer( + imgIContainer* aImage, uint32_t aWhichFrame, + const nsPresContext* aPresContext, const ComputedStyle* aComputedStyle, + NSImage** aResult, CGFloat scaleFactor, bool* aIsEntirelyBlack) { RefPtr surface; int32_t width = 0, height = 0; aImage->GetWidth(&width); @@ -487,10 +523,12 @@ nsresult nsCocoaUtils::CreateNSImageFromImageContainer(imgIContainer* aImage, ui // Render a vector image at the correct resolution on a retina display if (aImage->GetType() == imgIContainer::TYPE_VECTOR) { - IntSize scaledSize = IntSize::Ceil(width * scaleFactor, height * scaleFactor); + IntSize scaledSize = + IntSize::Ceil(width * scaleFactor, height * scaleFactor); - RefPtr drawTarget = gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget( - scaledSize, SurfaceFormat::B8G8R8A8); + RefPtr drawTarget = + gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget( + scaledSize, SurfaceFormat::B8G8R8A8); if (!drawTarget || !drawTarget->IsValid()) { NS_ERROR("Failed to create valid DrawTarget"); return NS_ERROR_FAILURE; @@ -500,11 +538,13 @@ nsresult nsCocoaUtils::CreateNSImageFromImageContainer(imgIContainer* aImage, ui SVGImageContext svgContext; if (aPresContext && aComputedStyle) { - SVGImageContext::MaybeStoreContextPaint(svgContext, *aPresContext, *aComputedStyle, aImage); + SVGImageContext::MaybeStoreContextPaint(svgContext, *aPresContext, + *aComputedStyle, aImage); } mozilla::image::ImgDrawResult res = - aImage->Draw(&context, scaledSize, ImageRegion::Create(scaledSize), aWhichFrame, - SamplingFilter::POINT, svgContext, imgIContainer::FLAG_SYNC_DECODE, 1.0); + aImage->Draw(&context, scaledSize, ImageRegion::Create(scaledSize), + aWhichFrame, SamplingFilter::POINT, svgContext, + imgIContainer::FLAG_SYNC_DECODE, 1.0); if (res != mozilla::image::ImgDrawResult::SUCCESS) { return NS_ERROR_FAILURE; @@ -512,14 +552,16 @@ nsresult nsCocoaUtils::CreateNSImageFromImageContainer(imgIContainer* aImage, ui surface = drawTarget->Snapshot(); } else { - surface = aImage->GetFrame(aWhichFrame, - imgIContainer::FLAG_SYNC_DECODE | imgIContainer::FLAG_ASYNC_NOTIFY); + surface = + aImage->GetFrame(aWhichFrame, imgIContainer::FLAG_SYNC_DECODE | + imgIContainer::FLAG_ASYNC_NOTIFY); } NS_ENSURE_TRUE(surface, NS_ERROR_FAILURE); CGImageRef imageRef = NULL; - nsresult rv = nsCocoaUtils::CreateCGImageFromSurface(surface, &imageRef, aIsEntirelyBlack); + nsresult rv = nsCocoaUtils::CreateCGImageFromSurface(surface, &imageRef, + aIsEntirelyBlack); if (NS_FAILED(rv) || !imageRef) { return NS_ERROR_FAILURE; } @@ -538,8 +580,9 @@ nsresult nsCocoaUtils::CreateNSImageFromImageContainer(imgIContainer* aImage, ui } nsresult nsCocoaUtils::CreateDualRepresentationNSImageFromImageContainer( - imgIContainer* aImage, uint32_t aWhichFrame, const nsPresContext* aPresContext, - const ComputedStyle* aComputedStyle, NSImage** aResult, bool* aIsEntirelyBlack) { + imgIContainer* aImage, uint32_t aWhichFrame, + const nsPresContext* aPresContext, const ComputedStyle* aComputedStyle, + NSImage** aResult, bool* aIsEntirelyBlack) { int32_t width = 0, height = 0; aImage->GetWidth(&width); aImage->GetHeight(&height); @@ -548,31 +591,36 @@ nsresult nsCocoaUtils::CreateDualRepresentationNSImageFromImageContainer( [*aResult setSize:size]; NSImage* newRepresentation = nil; - nsresult rv = CreateNSImageFromImageContainer(aImage, aWhichFrame, aPresContext, aComputedStyle, - &newRepresentation, 1.0f, aIsEntirelyBlack); + nsresult rv = CreateNSImageFromImageContainer( + aImage, aWhichFrame, aPresContext, aComputedStyle, &newRepresentation, + 1.0f, aIsEntirelyBlack); if (NS_FAILED(rv) || !newRepresentation) { return NS_ERROR_FAILURE; } [[[newRepresentation representations] objectAtIndex:0] setSize:size]; - [*aResult addRepresentation:[[newRepresentation representations] objectAtIndex:0]]; + [*aResult + addRepresentation:[[newRepresentation representations] objectAtIndex:0]]; [newRepresentation release]; newRepresentation = nil; - rv = CreateNSImageFromImageContainer(aImage, aWhichFrame, aPresContext, aComputedStyle, - &newRepresentation, 2.0f, aIsEntirelyBlack); + rv = CreateNSImageFromImageContainer(aImage, aWhichFrame, aPresContext, + aComputedStyle, &newRepresentation, 2.0f, + aIsEntirelyBlack); if (NS_FAILED(rv) || !newRepresentation) { return NS_ERROR_FAILURE; } [[[newRepresentation representations] objectAtIndex:0] setSize:size]; - [*aResult addRepresentation:[[newRepresentation representations] objectAtIndex:0]]; + [*aResult + addRepresentation:[[newRepresentation representations] objectAtIndex:0]]; [newRepresentation release]; return NS_OK; } // static -void nsCocoaUtils::GetStringForNSString(const NSString* aSrc, nsAString& aDist) { +void nsCocoaUtils::GetStringForNSString(const NSString* aSrc, + nsAString& aDist) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; if (!aSrc) { @@ -592,7 +640,8 @@ NSString* nsCocoaUtils::ToNSString(const nsAString& aString) { if (aString.IsEmpty()) { return [NSString string]; } - return [NSString stringWithCharacters:reinterpret_cast(aString.BeginReading()) + return [NSString stringWithCharacters:reinterpret_cast( + aString.BeginReading()) length:aString.Length()]; } @@ -609,7 +658,8 @@ NSString* nsCocoaUtils::ToNSString(const nsACString& aCString) { // static NSURL* nsCocoaUtils::ToNSURL(const nsAString& aURLString) { nsAutoCString encodedURLString; - nsresult rv = NS_GetSpecWithNSURLEncoding(encodedURLString, NS_ConvertUTF16toUTF8(aURLString)); + nsresult rv = NS_GetSpecWithNSURLEncoding(encodedURLString, + NS_ConvertUTF16toUTF8(aURLString)); NS_ENSURE_SUCCESS(rv, nullptr); NSString* encodedURLNSString = ToNSString(encodedURLString); @@ -621,7 +671,8 @@ NSURL* nsCocoaUtils::ToNSURL(const nsAString& aURLString) { } // static -void nsCocoaUtils::GeckoRectToNSRect(const nsIntRect& aGeckoRect, NSRect& aOutCocoaRect) { +void nsCocoaUtils::GeckoRectToNSRect(const nsIntRect& aGeckoRect, + NSRect& aOutCocoaRect) { aOutCocoaRect.origin.x = aGeckoRect.x; aOutCocoaRect.origin.y = aGeckoRect.y; aOutCocoaRect.size.width = aGeckoRect.width; @@ -629,37 +680,43 @@ void nsCocoaUtils::GeckoRectToNSRect(const nsIntRect& aGeckoRect, NSRect& aOutCo } // static -void nsCocoaUtils::NSRectToGeckoRect(const NSRect& aCocoaRect, nsIntRect& aOutGeckoRect) { +void nsCocoaUtils::NSRectToGeckoRect(const NSRect& aCocoaRect, + nsIntRect& aOutGeckoRect) { aOutGeckoRect.x = NSToIntRound(aCocoaRect.origin.x); aOutGeckoRect.y = NSToIntRound(aCocoaRect.origin.y); - aOutGeckoRect.width = NSToIntRound(aCocoaRect.origin.x + aCocoaRect.size.width) - aOutGeckoRect.x; + aOutGeckoRect.width = + NSToIntRound(aCocoaRect.origin.x + aCocoaRect.size.width) - + aOutGeckoRect.x; aOutGeckoRect.height = - NSToIntRound(aCocoaRect.origin.y + aCocoaRect.size.height) - aOutGeckoRect.y; + NSToIntRound(aCocoaRect.origin.y + aCocoaRect.size.height) - + aOutGeckoRect.y; } // static -NSEvent* nsCocoaUtils::MakeNewCocoaEventWithType(NSEventType aEventType, NSEvent* aEvent) { +NSEvent* nsCocoaUtils::MakeNewCocoaEventWithType(NSEventType aEventType, + NSEvent* aEvent) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - NSEvent* newEvent = [NSEvent keyEventWithType:aEventType - location:[aEvent locationInWindow] - modifierFlags:[aEvent modifierFlags] - timestamp:[aEvent timestamp] - windowNumber:[aEvent windowNumber] - context:nil - characters:[aEvent characters] - charactersIgnoringModifiers:[aEvent charactersIgnoringModifiers] - isARepeat:[aEvent isARepeat] - keyCode:[aEvent keyCode]]; + NSEvent* newEvent = + [NSEvent keyEventWithType:aEventType + location:[aEvent locationInWindow] + modifierFlags:[aEvent modifierFlags] + timestamp:[aEvent timestamp] + windowNumber:[aEvent windowNumber] + context:nil + characters:[aEvent characters] + charactersIgnoringModifiers:[aEvent charactersIgnoringModifiers] + isARepeat:[aEvent isARepeat] + keyCode:[aEvent keyCode]]; return newEvent; NS_OBJC_END_TRY_BLOCK_RETURN(nil); } // static -NSEvent* nsCocoaUtils::MakeNewCococaEventFromWidgetEvent(const WidgetKeyboardEvent& aKeyEvent, - NSInteger aWindowNumber, - NSGraphicsContext* aContext) { +NSEvent* nsCocoaUtils::MakeNewCococaEventFromWidgetEvent( + const WidgetKeyboardEvent& aKeyEvent, NSInteger aWindowNumber, + NSGraphicsContext* aContext) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; NSEventType eventType; @@ -669,13 +726,14 @@ NSEvent* nsCocoaUtils::MakeNewCococaEventFromWidgetEvent(const WidgetKeyboardEve eventType = NSEventTypeKeyDown; } - static const uint32_t sModifierFlagMap[][2] = {{MODIFIER_SHIFT, NSEventModifierFlagShift}, - {MODIFIER_CONTROL, NSEventModifierFlagControl}, - {MODIFIER_ALT, NSEventModifierFlagOption}, - {MODIFIER_ALTGRAPH, NSEventModifierFlagOption}, - {MODIFIER_META, NSEventModifierFlagCommand}, - {MODIFIER_CAPSLOCK, NSEventModifierFlagCapsLock}, - {MODIFIER_NUMLOCK, NSEventModifierFlagNumericPad}}; + static const uint32_t sModifierFlagMap[][2] = { + {MODIFIER_SHIFT, NSEventModifierFlagShift}, + {MODIFIER_CONTROL, NSEventModifierFlagControl}, + {MODIFIER_ALT, NSEventModifierFlagOption}, + {MODIFIER_ALTGRAPH, NSEventModifierFlagOption}, + {MODIFIER_META, NSEventModifierFlagCommand}, + {MODIFIER_CAPSLOCK, NSEventModifierFlagCapsLock}, + {MODIFIER_NUMLOCK, NSEventModifierFlagNumericPad}}; NSUInteger modifierFlags = 0; for (uint32_t i = 0; i < ArrayLength(sModifierFlagMap); ++i) { @@ -687,12 +745,15 @@ NSEvent* nsCocoaUtils::MakeNewCococaEventFromWidgetEvent(const WidgetKeyboardEve NSString* characters; if (aKeyEvent.mCharCode) { characters = - [NSString stringWithCharacters:reinterpret_cast(&(aKeyEvent.mCharCode)) + [NSString stringWithCharacters:reinterpret_cast( + &(aKeyEvent.mCharCode)) length:1]; } else { - uint32_t cocoaCharCode = nsCocoaUtils::ConvertGeckoKeyCodeToMacCharCode(aKeyEvent.mKeyCode); - characters = [NSString stringWithCharacters:reinterpret_cast(&cocoaCharCode) - length:1]; + uint32_t cocoaCharCode = + nsCocoaUtils::ConvertGeckoKeyCodeToMacCharCode(aKeyEvent.mKeyCode); + characters = [NSString + stringWithCharacters:reinterpret_cast(&cocoaCharCode) + length:1]; } return [NSEvent keyEventWithType:eventType @@ -710,7 +771,8 @@ NSEvent* nsCocoaUtils::MakeNewCococaEventFromWidgetEvent(const WidgetKeyboardEve } // static -void nsCocoaUtils::InitInputEvent(WidgetInputEvent& aInputEvent, NSEvent* aNativeEvent) { +void nsCocoaUtils::InitInputEvent(WidgetInputEvent& aInputEvent, + NSEvent* aNativeEvent) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; aInputEvent.mModifiers = ModifiersForEvent(aNativeEvent); @@ -721,7 +783,8 @@ void nsCocoaUtils::InitInputEvent(WidgetInputEvent& aInputEvent, NSEvent* aNativ // static Modifiers nsCocoaUtils::ModifiersForEvent(NSEvent* aNativeEvent) { - NSUInteger modifiers = aNativeEvent ? [aNativeEvent modifierFlags] : [NSEvent modifierFlags]; + NSUInteger modifiers = + aNativeEvent ? [aNativeEvent modifierFlags] : [NSEvent modifierFlags]; Modifiers result = 0; if (modifiers & NSEventModifierFlagShift) { result |= MODIFIER_SHIFT; @@ -755,9 +818,9 @@ Modifiers nsCocoaUtils::ModifiersForEvent(NSEvent* aNativeEvent) { result |= MODIFIER_NUMLOCK; } - // Be aware, NSEventModifierFlagFunction is included when arrow keys, home key or some - // other keys are pressed. We cannot check whether 'fn' key is pressed or - // not by the flag. + // Be aware, NSEventModifierFlagFunction is included when arrow keys, home key + // or some other keys are pressed. We cannot check whether 'fn' key is pressed + // or not by the flag. return result; } @@ -846,8 +909,8 @@ bool nsCocoaUtils::HiDPIEnabled() { // static void nsCocoaUtils::InvalidateHiDPIState() { sHiDPIPrefInitialized = false; } -void nsCocoaUtils::GetCommandsFromKeyEvent(NSEvent* aEvent, - nsTArray& aCommands) { +void nsCocoaUtils::GetCommandsFromKeyEvent( + NSEvent* aEvent, nsTArray& aCommands) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; MOZ_ASSERT(aEvent); @@ -860,7 +923,8 @@ void nsCocoaUtils::GetCommandsFromKeyEvent(NSEvent* aEvent, [sNativeKeyBindingsRecorder startRecording:aCommands]; // This will trigger 0 - N calls to doCommandBySelector: and insertText: - [sNativeKeyBindingsRecorder interpretKeyEvents:[NSArray arrayWithObject:aEvent]]; + [sNativeKeyBindingsRecorder + interpretKeyEvents:[NSArray arrayWithObject:aEvent]]; NS_OBJC_END_TRY_IGNORE_BLOCK; } @@ -1021,7 +1085,8 @@ static const KeyConversionData gKeyConversions[] = { }; -uint32_t nsCocoaUtils::ConvertGeckoNameToMacCharCode(const nsAString& aKeyCodeName) { +uint32_t nsCocoaUtils::ConvertGeckoNameToMacCharCode( + const nsAString& aKeyCodeName) { if (aKeyCodeName.IsEmpty()) { return 0; } @@ -1108,9 +1173,10 @@ mozilla::MouseButton nsCocoaUtils::ButtonForEvent(NSEvent* aEvent) { case 4: return MouseButton::eX2; default: - // The middle button usually has button 2, but if this is a synthesized event (for which - // you cannot specify a buttonNumber), then the button will be 0. Treat all remaining - // OtherMouse events as the middle button. + // The middle button usually has button 2, but if this is a + // synthesized event (for which you cannot specify a buttonNumber), + // then the button will be 0. Treat all remaining OtherMouse events as + // the middle button. return MouseButton::eMiddle; } default: @@ -1120,13 +1186,14 @@ mozilla::MouseButton nsCocoaUtils::ButtonForEvent(NSEvent* aEvent) { } NSMutableAttributedString* nsCocoaUtils::GetNSMutableAttributedString( - const nsAString& aText, const nsTArray& aFontRanges, const bool aIsVertical, - const CGFloat aBackingScaleFactor) { + const nsAString& aText, const nsTArray& aFontRanges, + const bool aIsVertical, const CGFloat aBackingScaleFactor) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN NSString* nsstr = nsCocoaUtils::ToNSString(aText); NSMutableAttributedString* attrStr = - [[[NSMutableAttributedString alloc] initWithString:nsstr attributes:nil] autorelease]; + [[[NSMutableAttributedString alloc] initWithString:nsstr + attributes:nil] autorelease]; int32_t lastOffset = aText.Length(); for (auto i = aFontRanges.Length(); i > 0; --i) { @@ -1139,7 +1206,8 @@ NSMutableAttributedString* nsCocoaUtils::GetNSMutableAttributedString( } NSDictionary* attrs = @{NSFontAttributeName : font}; - NSRange range = NSMakeRange(fontRange.mStartOffset, lastOffset - fontRange.mStartOffset); + NSRange range = NSMakeRange(fontRange.mStartOffset, + lastOffset - fontRange.mStartOffset); [attrStr setAttributes:attrs range:range]; lastOffset = fontRange.mStartOffset; } @@ -1167,7 +1235,8 @@ TimeStamp nsCocoaUtils::GetEventTimeStamp(NSTimeInterval aEventTime) { // Event timestamps are NSTimeIntervals (seconds) since boot. So the two time // representations already have the same base; we only need to convert // seconds into ticks. - int64_t tick = BaseTimeDurationPlatformUtils::TicksFromMilliseconds(aEventTime * 1000.0); + int64_t tick = + BaseTimeDurationPlatformUtils::TicksFromMilliseconds(aEventTime * 1000.0); return TimeStamp::FromSystemTime(tick); } @@ -1194,8 +1263,8 @@ bool nsCocoaUtils::ShouldZoomOnTitlebarDoubleClick() { bool nsCocoaUtils::ShouldMinimizeOnTitlebarDoubleClick() { // Check the system preferences. - // We could also check -[NSWindow _shouldMiniaturizeOnDoubleClick]. It's not clear to me which - // approach would be preferable; neither is public API. + // We could also check -[NSWindow _shouldMiniaturizeOnDoubleClick]. It's not + // clear to me which approach would be preferable; neither is public API. return [ActionOnDoubleClickSystemPref() isEqualToString:@"Minimize"]; } @@ -1261,11 +1330,13 @@ static nsresult GetPermissionState(AVMediaType aMediaType, uint16_t& aState) { } } -nsresult nsCocoaUtils::GetVideoCapturePermissionState(uint16_t& aPermissionState) { +nsresult nsCocoaUtils::GetVideoCapturePermissionState( + uint16_t& aPermissionState) { return GetPermissionState(AVMediaTypeVideo, aPermissionState); } -nsresult nsCocoaUtils::GetAudioCapturePermissionState(uint16_t& aPermissionState) { +nsresult nsCocoaUtils::GetAudioCapturePermissionState( + uint16_t& aPermissionState) { return GetPermissionState(AVMediaTypeAudio, aPermissionState); } @@ -1275,7 +1346,8 @@ nsresult nsCocoaUtils::GetAudioCapturePermissionState(uint16_t& aPermissionState // hasn't yet been asked yet or the user previously denied the prompt), use // PERMISSION_STATE_DENIED. Returns NS_ERROR_NOT_IMPLEMENTED on macOS 10.14 // and earlier. -nsresult nsCocoaUtils::GetScreenCapturePermissionState(uint16_t& aPermissionState) { +nsresult nsCocoaUtils::GetScreenCapturePermissionState( + uint16_t& aPermissionState) { aPermissionState = nsIOSPermissionRequest::PERMISSION_STATE_NOTDETERMINED; if (!StaticPrefs::media_macos_screenrecording_oscheck_enabled()) { @@ -1313,15 +1385,17 @@ nsresult nsCocoaUtils::GetScreenCapturePermissionState(uint16_t& aPermissionStat } for (CFIndex i = 0; i < windowCount; i++) { - CFDictionaryRef windowDict = - reinterpret_cast(CFArrayGetValueAtIndex(windowArray, i)); + CFDictionaryRef windowDict = reinterpret_cast( + CFArrayGetValueAtIndex(windowArray, i)); // Get the window owner's PID int32_t windowOwnerPid = -1; - CFNumberRef windowPidRef = - reinterpret_cast(CFDictionaryGetValue(windowDict, kCGWindowOwnerPID)); - if (!windowPidRef || !CFNumberGetValue(windowPidRef, kCFNumberIntType, &windowOwnerPid)) { - LOG("GetScreenCapturePermissionState() ERROR: failed to get window owner"); + CFNumberRef windowPidRef = reinterpret_cast( + CFDictionaryGetValue(windowDict, kCGWindowOwnerPID)); + if (!windowPidRef || + !CFNumberGetValue(windowPidRef, kCFNumberIntType, &windowOwnerPid)) { + LOG("GetScreenCapturePermissionState() ERROR: failed to get window " + "owner"); continue; } @@ -1331,16 +1405,17 @@ nsresult nsCocoaUtils::GetScreenCapturePermissionState(uint16_t& aPermissionStat continue; } - CFStringRef windowName = - reinterpret_cast(CFDictionaryGetValue(windowDict, kCGWindowName)); + CFStringRef windowName = reinterpret_cast( + CFDictionaryGetValue(windowDict, kCGWindowName)); if (!windowName) { continue; } - CFNumberRef windowLayerRef = - reinterpret_cast(CFDictionaryGetValue(windowDict, kCGWindowLayer)); + CFNumberRef windowLayerRef = reinterpret_cast( + CFDictionaryGetValue(windowDict, kCGWindowLayer)); int32_t windowLayer; - if (!windowLayerRef || !CFNumberGetValue(windowLayerRef, kCFNumberIntType, &windowLayer)) { + if (!windowLayerRef || + !CFNumberGetValue(windowLayerRef, kCFNumberIntType, &windowLayer)) { LOG("GetScreenCapturePermissionState() ERROR: failed to get layer"); continue; } @@ -1360,15 +1435,19 @@ nsresult nsCocoaUtils::GetScreenCapturePermissionState(uint16_t& aPermissionStat return NS_OK; } -nsresult nsCocoaUtils::RequestVideoCapturePermission(RefPtr& aPromise) { +nsresult nsCocoaUtils::RequestVideoCapturePermission( + RefPtr& aPromise) { MOZ_ASSERT(NS_IsMainThread()); - return nsCocoaUtils::RequestCapturePermission(AVMediaTypeVideo, aPromise, sVideoCapturePromises, + return nsCocoaUtils::RequestCapturePermission(AVMediaTypeVideo, aPromise, + sVideoCapturePromises, VideoCompletionHandler); } -nsresult nsCocoaUtils::RequestAudioCapturePermission(RefPtr& aPromise) { +nsresult nsCocoaUtils::RequestAudioCapturePermission( + RefPtr& aPromise) { MOZ_ASSERT(NS_IsMainThread()); - return nsCocoaUtils::RequestCapturePermission(AVMediaTypeAudio, aPromise, sAudioCapturePromises, + return nsCocoaUtils::RequestCapturePermission(AVMediaTypeAudio, aPromise, + sAudioCapturePromises, AudioCompletionHandler); } @@ -1380,9 +1459,9 @@ nsresult nsCocoaUtils::RequestAudioCapturePermission(RefPtr& aPromise) // request completes and must resolve any waiting Promises on the main // thread. // -nsresult nsCocoaUtils::RequestCapturePermission(AVMediaType aType, RefPtr& aPromise, - PromiseArray& aPromiseList, - void (^aHandler)(BOOL granted)) { +nsresult nsCocoaUtils::RequestCapturePermission( + AVMediaType aType, RefPtr& aPromise, PromiseArray& aPromiseList, + void (^aHandler)(BOOL granted)) { MOZ_ASSERT(aType == AVMediaTypeVideo || aType == AVMediaTypeAudio); LOG("RequestCapturePermission(%s)", AVMediaTypeToString(aType)); @@ -1399,8 +1478,8 @@ nsresult nsCocoaUtils::RequestCapturePermission(AVMediaType aType, RefPtr promise = aPromiseList->PopLastElement(); // Resolve on main thread - nsCOMPtr runnable(NS_NewRunnableFunction( - "ResolveMediaAccessPromise", - [aGranted, aPromise = std::move(promise)]() { aPromise->MaybeResolve(aGranted); })); + nsCOMPtr runnable( + NS_NewRunnableFunction("ResolveMediaAccessPromise", + [aGranted, aPromise = std::move(promise)]() { + aPromise->MaybeResolve(aGranted); + })); NS_DispatchToMainThread(runnable.forget()); } } void nsCocoaUtils::ResolveAudioCapturePromises(bool aGranted) { // Resolve on main thread - nsCOMPtr runnable(NS_NewRunnableFunction("ResolveAudioCapturePromise", [aGranted]() { - ResolveMediaCapturePromises(aGranted, sAudioCapturePromises); - })); + nsCOMPtr runnable( + NS_NewRunnableFunction("ResolveAudioCapturePromise", [aGranted]() { + ResolveMediaCapturePromises(aGranted, sAudioCapturePromises); + })); NS_DispatchToMainThread(runnable.forget()); } @@ -1470,9 +1553,10 @@ nsresult nsCocoaUtils::MaybeRequestScreenCapturePermission() { void nsCocoaUtils::ResolveVideoCapturePromises(bool aGranted) { // Resolve on main thread - nsCOMPtr runnable(NS_NewRunnableFunction("ResolveVideoCapturePromise", [aGranted]() { - ResolveMediaCapturePromises(aGranted, sVideoCapturePromises); - })); + nsCOMPtr runnable( + NS_NewRunnableFunction("ResolveVideoCapturePromise", [aGranted]() { + ResolveMediaCapturePromises(aGranted, sVideoCapturePromises); + })); NS_DispatchToMainThread(runnable.forget()); } @@ -1516,25 +1600,27 @@ bool static ShouldConsiderStartingSwipeFromEvent(NSEvent* anEvent) { // always a scroll (even in Safari). This preference can't (currently) be set // from the Preferences UI -- only using 'defaults write'. NSEventPhase eventPhase = [anEvent phase]; - return [anEvent type] == NSEventTypeScrollWheel && eventPhase == NSEventPhaseBegan && - [anEvent hasPreciseScrollingDeltas] && [NSEvent isSwipeTrackingFromScrollEventsEnabled]; + return [anEvent type] == NSEventTypeScrollWheel && + eventPhase == NSEventPhaseBegan && + [anEvent hasPreciseScrollingDeltas] && + [NSEvent isSwipeTrackingFromScrollEventsEnabled]; } -PanGestureInput nsCocoaUtils::CreatePanGestureEvent(NSEvent* aNativeEvent, TimeStamp aTimeStamp, - const ScreenPoint& aPanStartPoint, - const ScreenPoint& aPreciseDelta, - const gfx::IntPoint& aLineOrPageDelta, - Modifiers aModifiers) { +PanGestureInput nsCocoaUtils::CreatePanGestureEvent( + NSEvent* aNativeEvent, TimeStamp aTimeStamp, + const ScreenPoint& aPanStartPoint, const ScreenPoint& aPreciseDelta, + const gfx::IntPoint& aLineOrPageDelta, Modifiers aModifiers) { PanGestureInput::PanGestureType type = PanGestureTypeForEvent(aNativeEvent); // Always force zero deltas on event types that shouldn't cause any scrolling, // so that we don't dispatch DOM wheel events for them. - bool shouldIgnoreDeltas = - type == PanGestureInput::PANGESTURE_MAYSTART || type == PanGestureInput::PANGESTURE_CANCELLED; + bool shouldIgnoreDeltas = type == PanGestureInput::PANGESTURE_MAYSTART || + type == PanGestureInput::PANGESTURE_CANCELLED; PanGestureInput panEvent( - type, aTimeStamp, aPanStartPoint, !shouldIgnoreDeltas ? aPreciseDelta : ScreenPoint(), - aModifiers, - PanGestureInput::IsEligibleForSwipe(ShouldConsiderStartingSwipeFromEvent(aNativeEvent))); + type, aTimeStamp, aPanStartPoint, + !shouldIgnoreDeltas ? aPreciseDelta : ScreenPoint(), aModifiers, + PanGestureInput::IsEligibleForSwipe( + ShouldConsiderStartingSwipeFromEvent(aNativeEvent))); if (!shouldIgnoreDeltas) { panEvent.SetLineOrPageDeltas(aLineOrPageDelta.x, aLineOrPageDelta.y); @@ -1543,7 +1629,8 @@ PanGestureInput nsCocoaUtils::CreatePanGestureEvent(NSEvent* aNativeEvent, TimeS return panEvent; } -bool nsCocoaUtils::IsValidPasteboardType(NSString* aAvailableType, bool aAllowFileURL) { +bool nsCocoaUtils::IsValidPasteboardType(NSString* aAvailableType, + bool aAllowFileURL) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; // Prevent exposing fileURL for non-fileURL type. @@ -1552,7 +1639,10 @@ bool nsCocoaUtils::IsValidPasteboardType(NSString* aAvailableType, bool aAllowFi // kPublicUrlPboardType, since it conforms to kPublicUrlPboardType. bool isValid = true; if (!aAllowFileURL && - [aAvailableType isEqualToString:[UTIHelper stringFromPboardType:(NSString*)kUTTypeFileURL]]) { + [aAvailableType + isEqualToString:[UTIHelper + stringFromPboardType:(NSString*) + kUTTypeFileURL]]) { isValid = false; } @@ -1561,9 +1651,8 @@ bool nsCocoaUtils::IsValidPasteboardType(NSString* aAvailableType, bool aAllowFi NS_OBJC_END_TRY_BLOCK_RETURN(false); } -NSString* nsCocoaUtils::GetStringForTypeFromPasteboardItem(NSPasteboardItem* aItem, - const NSString* aType, - bool aAllowFileURL) { +NSString* nsCocoaUtils::GetStringForTypeFromPasteboardItem( + NSPasteboardItem* aItem, const NSString* aType, bool aAllowFileURL) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; NSString* availableType = @@ -1594,7 +1683,8 @@ NSString* nsCocoaUtils::GetFilePathFromPasteboardItem(NSPasteboardItem* aItem) { NS_OBJC_END_TRY_BLOCK_RETURN(nil); } -NSString* nsCocoaUtils::GetTitleForURLFromPasteboardItem(NSPasteboardItem* item) { +NSString* nsCocoaUtils::GetTitleForURLFromPasteboardItem( + NSPasteboardItem* item) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; NSString* name = nsCocoaUtils::GetStringForTypeFromPasteboardItem( @@ -1613,9 +1703,9 @@ NSString* nsCocoaUtils::GetTitleForURLFromPasteboardItem(NSPasteboardItem* item) NS_OBJC_END_TRY_BLOCK_RETURN(nil); } -void nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem(nsITransferable* aTransferable, - const nsCString& aFlavor, - NSPasteboardItem* aItem) { +void nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem( + nsITransferable* aTransferable, const nsCString& aFlavor, + NSPasteboardItem* aItem) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; if (!aTransferable || !aItem) { @@ -1623,7 +1713,8 @@ void nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem(nsITransferable* aTr } MOZ_LOG(gCocoaUtilsLog, LogLevel::Info, - ("nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem: looking for pasteboard data of " + ("nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem: looking " + "for pasteboard data of " "type %s\n", aFlavor.get())); @@ -1634,7 +1725,8 @@ void nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem(nsITransferable* aTr } unsigned int stringLength = [filePath length]; - unsigned int dataLength = (stringLength + 1) * sizeof(char16_t); // in bytes + unsigned int dataLength = + (stringLength + 1) * sizeof(char16_t); // in bytes char16_t* clipboardDataPtr = (char16_t*)malloc(dataLength); if (!clipboardDataPtr) { return; @@ -1644,7 +1736,8 @@ void nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem(nsITransferable* aTr clipboardDataPtr[stringLength] = 0; // null terminate nsCOMPtr file; - nsresult rv = NS_NewLocalFile(nsDependentString(clipboardDataPtr), true, getter_AddRefs(file)); + nsresult rv = NS_NewLocalFile(nsDependentString(clipboardDataPtr), true, + getter_AddRefs(file)); free(clipboardDataPtr); if (NS_FAILED(rv)) { return; @@ -1655,9 +1748,11 @@ void nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem(nsITransferable* aTr } if (aFlavor.EqualsLiteral(kCustomTypesMime)) { - NSString* availableType = - [aItem availableTypeFromArray:[NSArray arrayWithObject:kMozCustomTypesPboardType]]; - if (!availableType || !nsCocoaUtils::IsValidPasteboardType(availableType, false)) { + NSString* availableType = [aItem + availableTypeFromArray:[NSArray + arrayWithObject:kMozCustomTypesPboardType]]; + if (!availableType || + !nsCocoaUtils::IsValidPasteboardType(availableType, false)) { return; } NSData* pasteboardData = [aItem dataForType:availableType]; @@ -1673,8 +1768,9 @@ void nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem(nsITransferable* aTr [pasteboardData getBytes:clipboardDataPtr length:dataLength]; nsCOMPtr genericDataWrapper; - nsPrimitiveHelpers::CreatePrimitiveForData(aFlavor, clipboardDataPtr, dataLength, - getter_AddRefs(genericDataWrapper)); + nsPrimitiveHelpers::CreatePrimitiveForData( + aFlavor, clipboardDataPtr, dataLength, + getter_AddRefs(genericDataWrapper)); aTransferable->SetTransferData(aFlavor.get(), genericDataWrapper); free(clipboardDataPtr); @@ -1722,32 +1818,37 @@ void nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem(nsITransferable* aTr } [stringData getBytes:clipboardDataPtr length:dataLength]; - // The DOM only wants LF, so convert from MacOS line endings to DOM line endings. + // The DOM only wants LF, so convert from MacOS line endings to DOM line + // endings. int32_t signedDataLength = dataLength; - nsLinebreakHelpers::ConvertPlatformToDOMLinebreaks(isRTF, &clipboardDataPtr, &signedDataLength); + nsLinebreakHelpers::ConvertPlatformToDOMLinebreaks(isRTF, &clipboardDataPtr, + &signedDataLength); dataLength = signedDataLength; // skip BOM (Byte Order Mark to distinguish little or big endian) char16_t* clipboardDataPtrNoBOM = (char16_t*)clipboardDataPtr; - if ((dataLength > 2) && - ((clipboardDataPtrNoBOM[0] == 0xFEFF) || (clipboardDataPtrNoBOM[0] == 0xFFFE))) { + if ((dataLength > 2) && ((clipboardDataPtrNoBOM[0] == 0xFEFF) || + (clipboardDataPtrNoBOM[0] == 0xFFFE))) { dataLength -= sizeof(char16_t); clipboardDataPtrNoBOM += 1; } nsCOMPtr genericDataWrapper; - nsPrimitiveHelpers::CreatePrimitiveForData(aFlavor, clipboardDataPtrNoBOM, dataLength, - getter_AddRefs(genericDataWrapper)); + nsPrimitiveHelpers::CreatePrimitiveForData( + aFlavor, clipboardDataPtrNoBOM, dataLength, + getter_AddRefs(genericDataWrapper)); aTransferable->SetTransferData(aFlavor.get(), genericDataWrapper); free(clipboardDataPtr); return; } - // We have never supported this on Mac OS X, we should someday. Normally dragging images - // in is accomplished with a file path drag instead of the image data itself. + // We have never supported this on Mac OS X, we should someday. Normally + // dragging images in is accomplished with a file path drag instead of the + // image data itself. /* - if (aFlavor.EqualsLiteral(kPNGImageMime) || aFlavor.EqualsLiteral(kJPEGImageMime) || - aFlavor.EqualsLiteral(kJPGImageMime) || aFlavor.EqualsLiteral(kGIFImageMime)) { + if (aFlavor.EqualsLiteral(kPNGImageMime) || + aFlavor.EqualsLiteral(kJPEGImageMime) || aFlavor.EqualsLiteral(kJPGImageMime) + || aFlavor.EqualsLiteral(kGIFImageMime)) { } */ diff --git a/widget/cocoa/nsCocoaWindow.mm b/widget/cocoa/nsCocoaWindow.mm index f5297f909a7b..b33bab268324 100644 --- a/widget/cocoa/nsCocoaWindow.mm +++ b/widget/cocoa/nsCocoaWindow.mm @@ -1,4 +1,4 @@ -/* -*- Mode: Objective-C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this @@ -94,12 +94,14 @@ typedef enum { kCGSSpaceIncludesOthers = 1 << 1, kCGSSpaceIncludesUser = 1 << 2, - kCGSAllSpacesMask = kCGSSpaceIncludesCurrent | kCGSSpaceIncludesOthers | kCGSSpaceIncludesUser + kCGSAllSpacesMask = + kCGSSpaceIncludesCurrent | kCGSSpaceIncludesOthers | kCGSSpaceIncludesUser } CGSSpaceMask; static NSString* const CGSSpaceIDKey = @"ManagedSpaceID"; static NSString* const CGSSpacesKey = @"Spaces"; extern CGSConnection _CGSDefaultConnection(void); -extern CGError CGSSetWindowTransform(CGSConnection cid, CGSWindow wid, CGAffineTransform transform); +extern CGError CGSSetWindowTransform(CGSConnection cid, CGSWindow wid, + CGAffineTransform transform); } #define NS_APPSHELLSERVICE_CONTRACTID "@mozilla.org/appshell/appShellService;1" @@ -111,8 +113,8 @@ NS_IMPL_ISUPPORTS_INHERITED(nsCocoaWindow, Inherited, nsPIWidgetCocoa) // widget - whether or not the sheet is showing. |[mWindow isSheet]| will return // true *only when the sheet is actually showing*. Choose your test wisely. -static void RollUpPopups( - nsIRollupListener::AllowAnimations aAllowAnimations = nsIRollupListener::AllowAnimations::Yes) { +static void RollUpPopups(nsIRollupListener::AllowAnimations aAllowAnimations = + nsIRollupListener::AllowAnimations::Yes) { nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener(); NS_ENSURE_TRUE_VOID(rollupListener); @@ -124,8 +126,8 @@ static void RollUpPopups( if (!rollupWidget) { return; } - nsIRollupListener::RollupOptions options{0, nsIRollupListener::FlushViews::Yes, nullptr, - aAllowAnimations}; + nsIRollupListener::RollupOptions options{ + 0, nsIRollupListener::FlushViews::Yes, nullptr, aAllowAnimations}; rollupListener->Rollup(options); } @@ -170,7 +172,8 @@ void nsCocoaWindow::DestroyNativeWindow() { // Define a helper function for checking our fullscreen window status. bool (^inNativeFullscreen)(void) = ^{ - return ((mWindow.styleMask & NSFullScreenWindowMask) == NSFullScreenWindowMask); + return ((mWindow.styleMask & NSFullScreenWindowMask) == + NSFullScreenWindowMask); }; // If we are in native fullscreen, or we are in the middle of a native @@ -192,15 +195,18 @@ void nsCocoaWindow::DestroyNativeWindow() { // don't even enter this loop if mInProcessTransitions is true. bool haveRequestedFullscreenExit = false; NSRunLoop* localRunLoop = [NSRunLoop currentRunLoop]; - while (!mInProcessTransitions && (inNativeFullscreen() || WeAreInNativeTransition()) && - [localRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) { + while (!mInProcessTransitions && + (inNativeFullscreen() || WeAreInNativeTransition()) && + [localRunLoop runMode:NSDefaultRunLoopMode + beforeDate:[NSDate distantFuture]]) { // This loop continues to process events until mWindow is fully out // of native fullscreen. // Check to see if we should one-time request an exit from fullscreen. // We do this if we are in native fullscreen and no window is in a // native fullscreen transition. - if (!haveRequestedFullscreenExit && inNativeFullscreen() && CanStartNativeTransition()) { + if (!haveRequestedFullscreenExit && inNativeFullscreen() && + CanStartNativeTransition()) { [mWindow toggleFullScreen:nil]; haveRequestedFullscreenExit = true; } @@ -268,7 +274,8 @@ static NSScreen* FindTargetScreenForRect(const DesktopIntRect& aRect) { NSEnumerator* screenEnum = [[NSScreen screens] objectEnumerator]; int largestIntersectArea = 0; while (NSScreen* screen = [screenEnum nextObject]) { - DesktopIntRect screenRect = nsCocoaUtils::CocoaRectToGeckoRect([screen visibleFrame]); + DesktopIntRect screenRect = + nsCocoaUtils::CocoaRectToGeckoRect([screen visibleFrame]); screenRect = screenRect.Intersect(aRect); int area = screenRect.width * screenRect.height; if (area > largestIntersectArea) { @@ -282,12 +289,14 @@ static NSScreen* FindTargetScreenForRect(const DesktopIntRect& aRect) { // fits the rect to the screen that contains the largest area of it, // or to aScreen if a screen is passed in // NB: this operates with aRect in desktop pixels -static void FitRectToVisibleAreaForScreen(DesktopIntRect& aRect, NSScreen* aScreen) { +static void FitRectToVisibleAreaForScreen(DesktopIntRect& aRect, + NSScreen* aScreen) { if (!aScreen) { aScreen = FindTargetScreenForRect(aRect); } - DesktopIntRect screenBounds = nsCocoaUtils::CocoaRectToGeckoRect([aScreen visibleFrame]); + DesktopIntRect screenBounds = + nsCocoaUtils::CocoaRectToGeckoRect([aScreen visibleFrame]); if (aRect.width > screenBounds.width) { aRect.width = screenBounds.width; @@ -305,15 +314,18 @@ static void FitRectToVisibleAreaForScreen(DesktopIntRect& aRect, NSScreen* aScre // If the left/top edge of the window is off the screen in either direction, // then set the window to start at the left/top edge of the screen. - if (aRect.x < screenBounds.x || aRect.x > (screenBounds.x + screenBounds.width)) { + if (aRect.x < screenBounds.x || + aRect.x > (screenBounds.x + screenBounds.width)) { aRect.x = screenBounds.x; } - if (aRect.y < screenBounds.y || aRect.y > (screenBounds.y + screenBounds.height)) { + if (aRect.y < screenBounds.y || + aRect.y > (screenBounds.y + screenBounds.height)) { aRect.y = screenBounds.y; } } -DesktopToLayoutDeviceScale ParentBackingScaleFactor(nsIWidget* aParent, NSView* aParentView) { +DesktopToLayoutDeviceScale ParentBackingScaleFactor(nsIWidget* aParent, + NSView* aParentView) { if (aParent) { return aParent->GetDesktopToDeviceScale(); } @@ -327,9 +339,11 @@ DesktopToLayoutDeviceScale ParentBackingScaleFactor(nsIWidget* aParent, NSView* // Returns the screen rectangle for the given widget. // Child widgets are positioned relative to this rectangle. // Exactly one of the arguments must be non-null. -static DesktopRect GetWidgetScreenRectForChildren(nsIWidget* aWidget, NSView* aView) { +static DesktopRect GetWidgetScreenRectForChildren(nsIWidget* aWidget, + NSView* aView) { if (aWidget) { - mozilla::DesktopToLayoutDeviceScale scale = aWidget->GetDesktopToDeviceScale(); + mozilla::DesktopToLayoutDeviceScale scale = + aWidget->GetDesktopToDeviceScale(); if (aWidget->GetWindowType() == WindowType::Child) { return aWidget->GetScreenBounds() / scale; } @@ -340,7 +354,8 @@ static DesktopRect GetWidgetScreenRectForChildren(nsIWidget* aWidget, NSView* aV // 1. Transform the view rect into window coords. // The returned rect is in "origin bottom-left" coordinates. - NSRect rectInWindowCoordinatesOBL = [aView convertRect:[aView bounds] toView:nil]; + NSRect rectInWindowCoordinatesOBL = [aView convertRect:[aView bounds] + toView:nil]; // 2. Turn the window-coord rect into screen coords, still origin bottom-left. NSRect rectInScreenCoordinatesOBL = @@ -348,7 +363,8 @@ static DesktopRect GetWidgetScreenRectForChildren(nsIWidget* aWidget, NSView* aV // 3. Convert the NSRect to a DesktopRect. This will convert to coordinates // with the origin in the top left corner of the primary screen. - return DesktopRect(nsCocoaUtils::CocoaRectToGeckoRect(rectInScreenCoordinatesOBL)); + return DesktopRect( + nsCocoaUtils::CocoaRectToGeckoRect(rectInScreenCoordinatesOBL)); } // aRect here is specified in desktop pixels @@ -357,7 +373,8 @@ static DesktopRect GetWidgetScreenRectForChildren(nsIWidget* aWidget, NSView* aV // aRect.{x,y} are offsets from the origin of the parent window and not an // absolute position. nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent, - const DesktopIntRect& aRect, widget::InitData* aInitData) { + const DesktopIntRect& aRect, + widget::InitData* aInitData) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; // Because the hidden window is created outside of an event loop, @@ -387,20 +404,23 @@ nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent, // Do we have a parent widget? if (aParent || aNativeParent) { - DesktopRect parentDesktopRect = GetWidgetScreenRectForChildren(aParent, (NSView*)aNativeParent); + DesktopRect parentDesktopRect = + GetWidgetScreenRectForChildren(aParent, (NSView*)aNativeParent); parentOrigin = gfx::RoundedToInt(parentDesktopRect.TopLeft()); } DesktopIntRect widgetRect = aRect + parentOrigin; - nsresult rv = CreateNativeWindow(nsCocoaUtils::GeckoRectToCocoaRect(widgetRect), mBorderStyle, - false, aInitData->mIsPrivate); + nsresult rv = + CreateNativeWindow(nsCocoaUtils::GeckoRectToCocoaRect(widgetRect), + mBorderStyle, false, aInitData->mIsPrivate); NS_ENSURE_SUCCESS(rv, rv); if (mWindowType == WindowType::Popup) { // now we can convert widgetRect to device pixels for the window we created, // as the child view expects a rect expressed in the dev pix of its parent - LayoutDeviceIntRect devRect = RoundedToInt(newBounds * GetDesktopToDeviceScale()); + LayoutDeviceIntRect devRect = + RoundedToInt(newBounds * GetDesktopToDeviceScale()); return CreatePopupContentView(devRect, aInitData); } @@ -412,14 +432,16 @@ nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent, } nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent, - const LayoutDeviceIntRect& aRect, widget::InitData* aInitData) { - DesktopIntRect desktopRect = - RoundedToInt(aRect / ParentBackingScaleFactor(aParent, (NSView*)aNativeParent)); + const LayoutDeviceIntRect& aRect, + widget::InitData* aInitData) { + DesktopIntRect desktopRect = RoundedToInt( + aRect / ParentBackingScaleFactor(aParent, (NSView*)aNativeParent)); return Create(aParent, aNativeParent, desktopRect, aInitData); } static unsigned int WindowMaskForBorderStyle(BorderStyle aBorderStyle) { - bool allOrDefault = (aBorderStyle == BorderStyle::All || aBorderStyle == BorderStyle::Default); + bool allOrDefault = (aBorderStyle == BorderStyle::All || + aBorderStyle == BorderStyle::Default); /* Apple's docs on NSWindow styles say that "a window's style mask should * include NSWindowStyleMaskTitled if it includes any of the others [besides @@ -456,8 +478,10 @@ static unsigned int WindowMaskForBorderStyle(BorderStyle aBorderStyle) { // Otherwise, aRect.x/y specify the position of the window's frame relative to // the bottom of the menubar and aRect.width/height specify the size of the // content rect. -nsresult nsCocoaWindow::CreateNativeWindow(const NSRect& aRect, BorderStyle aBorderStyle, - bool aRectIsFrameRect, bool aIsPrivateBrowsing) { +nsresult nsCocoaWindow::CreateNativeWindow(const NSRect& aRect, + BorderStyle aBorderStyle, + bool aRectIsFrameRect, + bool aIsPrivateBrowsing) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; // We default to NSWindowStyleMaskBorderless, add features if needed. @@ -469,7 +493,8 @@ nsresult nsCocoaWindow::CreateNativeWindow(const NSRect& aRect, BorderStyle aBor case WindowType::Child: break; case WindowType::Popup: - if (aBorderStyle != BorderStyle::Default && mBorderStyle & BorderStyle::Title) { + if (aBorderStyle != BorderStyle::Default && + mBorderStyle & BorderStyle::Title) { features |= NSWindowStyleMaskTitled; if (aBorderStyle & BorderStyle::Close) { features |= NSWindowStyleMaskClosable; @@ -518,24 +543,28 @@ nsresult nsCocoaWindow::CreateNativeWindow(const NSRect& aRect, BorderStyle aBor * Note: If you pass a rect with 0,0 for an origin, the window ends up in a * weird place for some reason. This stops that without breaking popups. */ - // Compensate for difference between frame and content area height (e.g. title bar). - NSRect newWindowFrame = [NSWindow frameRectForContentRect:aRect styleMask:features]; + // Compensate for difference between frame and content area height (e.g. + // title bar). + NSRect newWindowFrame = [NSWindow frameRectForContentRect:aRect + styleMask:features]; contentRect = aRect; contentRect.origin.y -= (newWindowFrame.size.height - aRect.size.height); - if (mWindowType != WindowType::Popup) contentRect.origin.y -= [[NSApp mainMenu] menuBarHeight]; + if (mWindowType != WindowType::Popup) + contentRect.origin.y -= [[NSApp mainMenu] menuBarHeight]; } // NSLog(@"Top-level window being created at Cocoa rect: %f, %f, %f, %f\n", // rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); Class windowClass = [BaseWindow class]; - // If we have a titlebar on a top-level window, we want to be able to control the - // titlebar color (for unified windows), so use the special ToolbarWindow class. - // Note that we need to check the window type because we mark sheets as + // If we have a titlebar on a top-level window, we want to be able to control + // the titlebar color (for unified windows), so use the special ToolbarWindow + // class. Note that we need to check the window type because we mark sheets as // having titlebars. - if ((mWindowType == WindowType::TopLevel || mWindowType == WindowType::Dialog) && + if ((mWindowType == WindowType::TopLevel || + mWindowType == WindowType::Dialog) && (features & NSWindowStyleMaskTitled)) windowClass = [ToolbarWindow class]; // If we're a popup window we need to use the PopupWindow class. @@ -615,8 +644,8 @@ nsresult nsCocoaWindow::CreateNativeWindow(const NSRect& aRect, BorderStyle aBor [[WindowDataMap sharedWindowDataMap] ensureDataForWindow:mWindow]; mWindowMadeHere = true; - // Make the window respect the global appearance, which follows the browser.theme.toolbar-theme - // pref. + // Make the window respect the global appearance, which follows the + // browser.theme.toolbar-theme pref. mWindow.appearanceSource = MOZGlobalAppearance.sharedInstance; return NS_OK; @@ -635,13 +664,15 @@ nsresult nsCocoaWindow::CreatePopupContentView(const LayoutDeviceIntRect& aRect, NS_ADDREF(mPopupContentView); nsIWidget* thisAsWidget = static_cast(this); - nsresult rv = mPopupContentView->Create(thisAsWidget, nullptr, aRect, aInitData); + nsresult rv = + mPopupContentView->Create(thisAsWidget, nullptr, aRect, aInitData); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } NSView* contentView = [mWindow contentView]; - ChildView* childView = (ChildView*)mPopupContentView->GetNativeData(NS_NATIVE_WIDGET); + ChildView* childView = + (ChildView*)mPopupContentView->GetNativeData(NS_NATIVE_WIDGET); [childView setFrame:[contentView bounds]]; [childView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [contentView addSubview:childView]; @@ -787,7 +818,8 @@ void nsCocoaWindow::SetModal(bool aState) { NSWindow* aWindow = ancestor->GetCocoaWindow(); if (ancestor->mWindowType != WindowType::Invisible) { [[aWindow standardWindowButton:NSWindowCloseButton] setEnabled:NO]; - [[aWindow standardWindowButton:NSWindowMiniaturizeButton] setEnabled:NO]; + [[aWindow standardWindowButton:NSWindowMiniaturizeButton] + setEnabled:NO]; [[aWindow standardWindowButton:NSWindowZoomButton] setEnabled:NO]; } } @@ -803,18 +835,21 @@ void nsCocoaWindow::SetModal(bool aState) { } } else { --gXULModalLevel; - NS_ASSERTION(gXULModalLevel >= 0, "Mismatched call to nsCocoaWindow::SetModal(false)!"); + NS_ASSERTION(gXULModalLevel >= 0, + "Mismatched call to nsCocoaWindow::SetModal(false)!"); if (mWindowType != WindowType::Sheet) { while (ancestor) { if (--ancestor->mNumModalDescendents == 0) { NSWindow* aWindow = ancestor->GetCocoaWindow(); if (ancestor->mWindowType != WindowType::Invisible) { [[aWindow standardWindowButton:NSWindowCloseButton] setEnabled:YES]; - [[aWindow standardWindowButton:NSWindowMiniaturizeButton] setEnabled:YES]; + [[aWindow standardWindowButton:NSWindowMiniaturizeButton] + setEnabled:YES]; [[aWindow standardWindowButton:NSWindowZoomButton] setEnabled:YES]; } } - NS_ASSERTION(ancestor->mNumModalDescendents >= 0, "Widget hierarchy changed while modal!"); + NS_ASSERTION(ancestor->mNumModalDescendents >= 0, + "Widget hierarchy changed while modal!"); ancestor = static_cast(ancestor->mParent); } if (gGeckoAppModalWindowList) { @@ -848,7 +883,8 @@ void nsCocoaWindow::Show(bool bState) { if (!mWindow) return; if (!mSheetNeedsShow) { - // Early exit if our current visibility state is already the requested state. + // Early exit if our current visibility state is already the requested + // state. if (bState == ([mWindow isVisible] || [mWindow isBeingShown])) { return; } @@ -862,12 +898,13 @@ void nsCocoaWindow::Show(bool bState) { nsIWidget* parentWidget = mParent; nsCOMPtr piParentWidget(do_QueryInterface(parentWidget)); NSWindow* nativeParentWindow = - (parentWidget) ? (NSWindow*)parentWidget->GetNativeData(NS_NATIVE_WINDOW) : nil; + (parentWidget) ? (NSWindow*)parentWidget->GetNativeData(NS_NATIVE_WINDOW) + : nil; if (bState && !mBounds.IsEmpty()) { // If we had set the activationPolicy to accessory, then right now we won't - // have a dock icon. Make sure that we undo that and show a dock icon now that - // we're going to show a window. + // have a dock icon. Make sure that we undo that and show a dock icon now + // that we're going to show a window. if ([NSApp activationPolicy] != NSApplicationActivationPolicyRegular) { [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; PR_SetEnv("MOZ_APP_NO_DOCK="); @@ -875,7 +912,8 @@ void nsCocoaWindow::Show(bool bState) { // Don't try to show a popup when the parent isn't visible or is minimized. if (mWindowType == WindowType::Popup && nativeParentWindow) { - if (![nativeParentWindow isVisible] || [nativeParentWindow isMiniaturized]) { + if (![nativeParentWindow isVisible] || + [nativeParentWindow isMiniaturized]) { return; } } @@ -896,7 +934,8 @@ void nsCocoaWindow::Show(bool bState) { // that is only used to handle sibling sheet contention. The parent will // return once there are no more child sheets. bool parentIsSheet = false; - if (NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) && parentIsSheet) { + if (NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) && + parentIsSheet) { piParentWidget->GetSheetWindowParent(&topNonSheetWindow); #ifdef MOZ_THUNDERBIRD [NSApp endSheet:nativeParentWindow]; @@ -906,7 +945,8 @@ void nsCocoaWindow::Show(bool bState) { } nsCOMPtr sheetShown; - if (NS_SUCCEEDED(piParentWidget->GetChildSheet(true, getter_AddRefs(sheetShown))) && + if (NS_SUCCEEDED(piParentWidget->GetChildSheet( + true, getter_AddRefs(sheetShown))) && (!sheetShown || sheetShown == this)) { // If this sheet is already the sheet actually being shown, don't // tell it to show again. Otherwise the number of calls to @@ -933,12 +973,15 @@ void nsCocoaWindow::Show(bool bState) { [TopLevelWindowData deactivateInWindow:mSheetWindowParent]; [mSheetWindowParent beginSheet:sheet completionHandler:^(NSModalResponse returnCode) { - // Note: 'nonSheetParent' (if it is set) is the window that is the parent - // of the sheet. If it's set, 'nonSheetParent' is always the top- level - // window, not another sheet itself. But 'nonSheetParent' is nil if our - // parent window is also a sheet -- in that case we shouldn't send the - // top-level window any activate events (because it's our parent window - // that needs to get these events, not the top-level window). + // Note: 'nonSheetParent' (if it is set) is the window + // that is the parent of the sheet. If it's set, + // 'nonSheetParent' is always the top- level window, + // not another sheet itself. But 'nonSheetParent' is + // nil if our parent window is also a sheet -- in that + // case we shouldn't send the top-level window any + // activate events (because it's our parent window that + // needs to get these events, not the top-level + // window). [TopLevelWindowData deactivateInWindow:sheet]; [sheet orderOut:nil]; if (nonSheetParent) { @@ -969,9 +1012,11 @@ void nsCocoaWindow::Show(bool bState) { // If our popup window is a non-native context menu, tell the OS (and // other programs) that a menu has opened. This is how the OS knows to // close other programs' context menus when ours open. - if ([mWindow isKindOfClass:[PopupWindow class]] && [(PopupWindow*)mWindow isContextMenu]) { + if ([mWindow isKindOfClass:[PopupWindow class]] && + [(PopupWindow*)mWindow isContextMenu]) { [[NSDistributedNotificationCenter defaultCenter] - postNotificationName:@"com.apple.HIToolbox.beginMenuTrackingNotification" + postNotificationName: + @"com.apple.HIToolbox.beginMenuTrackingNotification" object:@"org.mozilla.gecko.PopupWindow"]; } @@ -1017,7 +1062,8 @@ void nsCocoaWindow::Show(bool bState) { } } else { // roll up any popups if a top-level window is going away - if (mWindowType == WindowType::TopLevel || mWindowType == WindowType::Dialog) { + if (mWindowType == WindowType::TopLevel || + mWindowType == WindowType::Dialog) { RollUpPopups(); } @@ -1029,7 +1075,8 @@ void nsCocoaWindow::Show(bool bState) { // won't show. mSheetNeedsShow = false; } else { - // get sheet's parent *before* hiding the sheet (which breaks the linkage) + // get sheet's parent *before* hiding the sheet (which breaks the + // linkage) NSWindow* sheetParent = mSheetWindowParent; // hide the sheet @@ -1044,29 +1091,32 @@ void nsCocoaWindow::Show(bool bState) { bool parentIsSheet = false; if (nativeParentWindow && piParentWidget && - NS_SUCCEEDED( - piParentWidget->GetChildSheet(false, getter_AddRefs(siblingSheetToShow))) && + NS_SUCCEEDED(piParentWidget->GetChildSheet( + false, getter_AddRefs(siblingSheetToShow))) && siblingSheetToShow) { // First, give sibling sheets an opportunity to show. siblingSheetToShow->Show(true); } else if (nativeParentWindow && piParentWidget && - NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) && parentIsSheet) { + NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) && + parentIsSheet) { #ifdef MOZ_THUNDERBIRD // Only set contextInfo if the parent of the parent sheet we're about // to restore isn't itself a sheet. NSWindow* contextInfo = sheetParent; #else - // Only set nonSheetGrandparent if the parent of the parent sheet we're about - // to restore isn't itself a sheet. + // Only set nonSheetGrandparent if the parent of the parent sheet + // we're about to restore isn't itself a sheet. NSWindow* nonSheetGrandparent = sheetParent; #endif nsIWidget* grandparentWidget = nil; if (NS_SUCCEEDED(piParentWidget->GetRealParent(&grandparentWidget)) && grandparentWidget) { - nsCOMPtr piGrandparentWidget(do_QueryInterface(grandparentWidget)); + nsCOMPtr piGrandparentWidget( + do_QueryInterface(grandparentWidget)); bool grandparentIsSheet = false; if (piGrandparentWidget && - NS_SUCCEEDED(piGrandparentWidget->GetIsSheet(&grandparentIsSheet)) && + NS_SUCCEEDED( + piGrandparentWidget->GetIsSheet(&grandparentIsSheet)) && grandparentIsSheet) { #ifdef MOZ_THUNDERBIRD contextInfo = nil; @@ -1085,20 +1135,23 @@ void nsCocoaWindow::Show(bool bState) { didEndSelector:@selector(didEndSheet:returnCode:contextInfo:) contextInfo:contextInfo]; #else - [nativeParentWindow beginSheet:sheetParent - completionHandler:^(NSModalResponse returnCode) { - // Note: 'nonSheetGrandparent' (if it is set) is the window that is the - // parent of sheetParent. If it's set, 'nonSheetGrandparent' is always the - // top-level window, not another sheet itself. But 'nonSheetGrandparent' - // is nil if our parent window is also a sheet -- in that case we shouldn't - // send the top-level window any activate events (because it's our parent - // window that needs to get these events, not the top-level window). - [TopLevelWindowData deactivateInWindow:sheetParent]; - [sheetParent orderOut:nil]; - if (nonSheetGrandparent) { - [TopLevelWindowData activateInWindow:nonSheetGrandparent]; - } - }]; + [nativeParentWindow + beginSheet:sheetParent + completionHandler:^(NSModalResponse returnCode) { + // Note: 'nonSheetGrandparent' (if it is set) is the window that + // is the parent of sheetParent. If it's set, + // 'nonSheetGrandparent' is always the top-level window, not + // another sheet itself. But 'nonSheetGrandparent' is nil if + // our parent window is also a sheet -- in that case we + // shouldn't send the top-level window any activate events + // (because it's our parent window that needs to get these + // events, not the top-level window). + [TopLevelWindowData deactivateInWindow:sheetParent]; + [sheetParent orderOut:nil]; + if (nonSheetGrandparent) { + [TopLevelWindowData activateInWindow:nonSheetGrandparent]; + } + }]; #endif } else { // Sheet, that was hard. No more siblings or parents, going back @@ -1120,9 +1173,11 @@ void nsCocoaWindow::Show(bool bState) { // If our popup window is a non-native context menu, tell the OS (and // other programs) that a menu has closed. - if ([mWindow isKindOfClass:[PopupWindow class]] && [(PopupWindow*)mWindow isContextMenu]) { + if ([mWindow isKindOfClass:[PopupWindow class]] && + [(PopupWindow*)mWindow isContextMenu]) { [[NSDistributedNotificationCenter defaultCenter] - postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification" + postNotificationName: + @"com.apple.HIToolbox.endMenuTrackingNotification" object:@"org.mozilla.gecko.PopupWindow"]; } } @@ -1141,7 +1196,8 @@ void nsCocoaWindow::Show(bool bState) { bool nsCocoaWindow::NeedsRecreateToReshow() { // Limit the workaround to popup windows because only they need to override // the "Assign To" setting. i.e., to display where the parent window is. - return (mWindowType == WindowType::Popup) && mWasShown && ([[NSScreen screens] count] > 1); + return (mWindowType == WindowType::Popup) && mWasShown && + ([[NSScreen screens] count] > 1); } WindowRenderer* nsCocoaWindow::GetWindowRenderer() { @@ -1173,7 +1229,8 @@ void nsCocoaWindow::SetTransparencyMode(TransparencyMode aMode) { BOOL currentTransparency = ![mWindow isOpaque]; if (isTransparent != currentTransparency) { [mWindow setOpaque:!isTransparent]; - [mWindow setBackgroundColor:(isTransparent ? [NSColor clearColor] : [NSColor whiteColor])]; + [mWindow setBackgroundColor:(isTransparent ? [NSColor clearColor] + : [NSColor whiteColor])]; } NS_OBJC_END_TRY_IGNORE_BLOCK; @@ -1200,14 +1257,16 @@ void nsCocoaWindow::ConstrainPosition(DesktopIntPoint& aPoint) { width = std::max(frame.size.width, 1); height = std::max(frame.size.height, 1); - nsCOMPtr screenMgr = do_GetService("@mozilla.org/gfx/screenmanager;1"); + nsCOMPtr screenMgr = + do_GetService("@mozilla.org/gfx/screenmanager;1"); if (screenMgr) { nsCOMPtr screen; - screenMgr->ScreenForRect(aPoint.x, aPoint.y, width, height, getter_AddRefs(screen)); + screenMgr->ScreenForRect(aPoint.x, aPoint.y, width, height, + getter_AddRefs(screen)); if (screen) { - screen->GetRectDisplayPix(&(screenBounds.x), &(screenBounds.y), &(screenBounds.width), - &(screenBounds.height)); + screen->GetRectDisplayPix(&(screenBounds.x), &(screenBounds.y), + &(screenBounds.width), &(screenBounds.height)); } } @@ -1230,7 +1289,9 @@ void nsCocoaWindow::SetSizeConstraints(const SizeConstraints& aConstraints) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; // Popups can be smaller than (32, 32) - NSRect rect = (mWindowType == WindowType::Popup) ? NSZeroRect : NSMakeRect(0.0, 0.0, 32, 32); + NSRect rect = (mWindowType == WindowType::Popup) + ? NSZeroRect + : NSMakeRect(0.0, 0.0, 32, 32); rect = [mWindow frameRectForChildViewRect:rect]; SizeConstraints c = aConstraints; @@ -1239,26 +1300,32 @@ void nsCocoaWindow::SetSizeConstraints(const SizeConstraints& aConstraints) { c.mScale.scale = BackingScaleFactor(); } - c.mMinSize.width = std::max(nsCocoaUtils::CocoaPointsToDevPixels(rect.size.width, c.mScale.scale), - c.mMinSize.width); + c.mMinSize.width = std::max( + nsCocoaUtils::CocoaPointsToDevPixels(rect.size.width, c.mScale.scale), + c.mMinSize.width); c.mMinSize.height = std::max( - nsCocoaUtils::CocoaPointsToDevPixels(rect.size.height, c.mScale.scale), c.mMinSize.height); + nsCocoaUtils::CocoaPointsToDevPixels(rect.size.height, c.mScale.scale), + c.mMinSize.height); - NSSize minSize = {nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.width, c.mScale.scale), - nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.height, c.mScale.scale)}; + NSSize minSize = { + nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.width, c.mScale.scale), + nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.height, c.mScale.scale)}; [mWindow setMinSize:minSize]; c.mMaxSize.width = std::max( - nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.width, c.mScale.scale), c.mMaxSize.width); + nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.width, c.mScale.scale), + c.mMaxSize.width); c.mMaxSize.height = std::max( - nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.height, c.mScale.scale), c.mMaxSize.height); + nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.height, c.mScale.scale), + c.mMaxSize.height); - NSSize maxSize = {c.mMaxSize.width == NS_MAXSIZE - ? FLT_MAX - : nsCocoaUtils::DevPixelsToCocoaPoints(c.mMaxSize.width, c.mScale.scale), - c.mMaxSize.height == NS_MAXSIZE - ? FLT_MAX - : nsCocoaUtils::DevPixelsToCocoaPoints(c.mMaxSize.height, c.mScale.scale)}; + NSSize maxSize = { + c.mMaxSize.width == NS_MAXSIZE ? FLT_MAX + : nsCocoaUtils::DevPixelsToCocoaPoints( + c.mMaxSize.width, c.mScale.scale), + c.mMaxSize.height == NS_MAXSIZE ? FLT_MAX + : nsCocoaUtils::DevPixelsToCocoaPoints( + c.mMaxSize.height, c.mScale.scale)}; [mWindow setMaxSize:maxSize]; nsBaseWidget::SetSizeConstraints(c); @@ -1276,11 +1343,13 @@ void nsCocoaWindow::Move(double aX, double aY) { // The point we have is in Gecko coordinates (origin top-left). Convert // it to Cocoa ones (origin bottom-left). - NSPoint coord = {static_cast(aX), - static_cast(nsCocoaUtils::FlippedScreenY(NSToIntRound(aY)))}; + NSPoint coord = { + static_cast(aX), + static_cast(nsCocoaUtils::FlippedScreenY(NSToIntRound(aY)))}; NSRect frame = [mWindow frame]; - if (frame.origin.x != coord.x || frame.origin.y + frame.size.height != coord.y) { + if (frame.origin.x != coord.x || + frame.origin.y + frame.size.height != coord.y) { [mWindow setFrameTopLeftPoint:coord]; } @@ -1320,43 +1389,50 @@ static CGSCopyManagedDisplaySpacesFunc GetCGSCopyManagedDisplaySpacesFunc() { static CGSCopyManagedDisplaySpacesFunc func = nullptr; static bool lookedUpFunc = false; if (!lookedUpFunc) { - func = (CGSCopyManagedDisplaySpacesFunc)dlsym(RTLD_DEFAULT, "CGSCopyManagedDisplaySpaces"); + func = (CGSCopyManagedDisplaySpacesFunc)dlsym( + RTLD_DEFAULT, "CGSCopyManagedDisplaySpaces"); lookedUpFunc = true; } return func; } // Runtime `CGSCopySpacesForWindows` library function feature detection. -typedef CFArrayRef (*CGSCopySpacesForWindowsFunc)(CGSConnection cid, CGSSpaceMask mask, +typedef CFArrayRef (*CGSCopySpacesForWindowsFunc)(CGSConnection cid, + CGSSpaceMask mask, CFArrayRef windowIDs); static CGSCopySpacesForWindowsFunc GetCGSCopySpacesForWindowsFunc() { static CGSCopySpacesForWindowsFunc func = nullptr; static bool lookedUpFunc = false; if (!lookedUpFunc) { - func = (CGSCopySpacesForWindowsFunc)dlsym(RTLD_DEFAULT, "CGSCopySpacesForWindows"); + func = (CGSCopySpacesForWindowsFunc)dlsym(RTLD_DEFAULT, + "CGSCopySpacesForWindows"); lookedUpFunc = true; } return func; } // Runtime `CGSAddWindowsToSpaces` library function feature detection. -typedef void (*CGSAddWindowsToSpacesFunc)(CGSConnection cid, CFArrayRef windowIDs, +typedef void (*CGSAddWindowsToSpacesFunc)(CGSConnection cid, + CFArrayRef windowIDs, CFArrayRef spaceIDs); static CGSAddWindowsToSpacesFunc GetCGSAddWindowsToSpacesFunc() { static CGSAddWindowsToSpacesFunc func = nullptr; static bool lookedUpFunc = false; if (!lookedUpFunc) { - func = (CGSAddWindowsToSpacesFunc)dlsym(RTLD_DEFAULT, "CGSAddWindowsToSpaces"); + func = + (CGSAddWindowsToSpacesFunc)dlsym(RTLD_DEFAULT, "CGSAddWindowsToSpaces"); lookedUpFunc = true; } return func; } // Runtime `CGSRemoveWindowsFromSpaces` library function feature detection. -typedef void (*CGSRemoveWindowsFromSpacesFunc)(CGSConnection cid, CFArrayRef windowIDs, +typedef void (*CGSRemoveWindowsFromSpacesFunc)(CGSConnection cid, + CFArrayRef windowIDs, CFArrayRef spaceIDs); static CGSRemoveWindowsFromSpacesFunc GetCGSRemoveWindowsFromSpacesFunc() { static CGSRemoveWindowsFromSpacesFunc func = nullptr; static bool lookedUpFunc = false; if (!lookedUpFunc) { - func = (CGSRemoveWindowsFromSpacesFunc)dlsym(RTLD_DEFAULT, "CGSRemoveWindowsFromSpaces"); + func = (CGSRemoveWindowsFromSpacesFunc)dlsym(RTLD_DEFAULT, + "CGSRemoveWindowsFromSpaces"); lookedUpFunc = true; } return func; @@ -1377,7 +1453,8 @@ int32_t nsCocoaWindow::GetWorkspaceID() { // effectively. CGSSpaceID sid = 0; - CGSCopySpacesForWindowsFunc CopySpacesForWindows = GetCGSCopySpacesForWindowsFunc(); + CGSCopySpacesForWindowsFunc CopySpacesForWindows = + GetCGSCopySpacesForWindowsFunc(); if (!CopySpacesForWindows) { return sid; } @@ -1385,7 +1462,8 @@ int32_t nsCocoaWindow::GetWorkspaceID() { CGSConnection cid = _CGSDefaultConnection(); // Fetch all spaces that this window belongs to (in order). NSArray* spaceIDs = CFBridgingRelease(CopySpacesForWindows( - cid, kCGSAllSpacesMask, (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ])); + cid, kCGSAllSpacesMask, + (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ])); if ([spaceIDs count]) { // When spaces are found, return the first one. // We don't support a single window painted across multiple places for now. @@ -1427,10 +1505,13 @@ void nsCocoaWindow::MoveToWorkspace(const nsAString& workspaceIDStr) { return; } - CGSCopyManagedDisplaySpacesFunc CopyManagedDisplaySpaces = GetCGSCopyManagedDisplaySpacesFunc(); + CGSCopyManagedDisplaySpacesFunc CopyManagedDisplaySpaces = + GetCGSCopyManagedDisplaySpacesFunc(); CGSAddWindowsToSpacesFunc AddWindowsToSpaces = GetCGSAddWindowsToSpacesFunc(); - CGSRemoveWindowsFromSpacesFunc RemoveWindowsFromSpaces = GetCGSRemoveWindowsFromSpacesFunc(); - if (!CopyManagedDisplaySpaces || !AddWindowsToSpaces || !RemoveWindowsFromSpaces) { + CGSRemoveWindowsFromSpacesFunc RemoveWindowsFromSpaces = + GetCGSRemoveWindowsFromSpacesFunc(); + if (!CopyManagedDisplaySpaces || !AddWindowsToSpaces || + !RemoveWindowsFromSpaces) { return; } @@ -1440,7 +1521,8 @@ void nsCocoaWindow::MoveToWorkspace(const nsAString& workspaceIDStr) { // early, which this local variable is used for. BOOL found = false; for (NSDictionary* spacesInfo in displaySpacesInfo) { - NSArray* sids = [spacesInfo[CGSSpacesKey] valueForKey:CGSSpaceIDKey]; + NSArray* sids = + [spacesInfo[CGSSpacesKey] valueForKey:CGSSpaceIDKey]; for (NSNumber* sid in sids) { // If we found our space in the list, we're good to go and can jump out of // this loop. @@ -1464,7 +1546,8 @@ void nsCocoaWindow::MoveToWorkspace(const nsAString& workspaceIDStr) { AddWindowsToSpaces(cid, (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ], (__bridge CFArrayRef) @[ @(workspaceID) ]); // Then we remove the window from the active space. - RemoveWindowsFromSpaces(cid, (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ], + RemoveWindowsFromSpaces(cid, + (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ], (__bridge CFArrayRef) @[ @(currentSpace) ]); NS_OBJC_END_TRY_IGNORE_BLOCK; @@ -1489,7 +1572,8 @@ void nsCocoaWindow::HideWindowChrome(bool aShouldHide) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; if (!mWindow || !mWindowMadeHere || - (mWindowType != WindowType::TopLevel && mWindowType != WindowType::Dialog)) + (mWindowType != WindowType::TopLevel && + mWindowType != WindowType::Dialog)) return; BOOL isVisible = [mWindow isVisible]; @@ -1515,8 +1599,9 @@ void nsCocoaWindow::HideWindowChrome(bool aShouldHide) { // Recreate the window with the right border style. NSRect frameRect = [mWindow frame]; DestroyNativeWindow(); - nsresult rv = CreateNativeWindow(frameRect, aShouldHide ? BorderStyle::None : mBorderStyle, true, - mWindow.restorable); + nsresult rv = CreateNativeWindow( + frameRect, aShouldHide ? BorderStyle::None : mBorderStyle, true, + mWindow.restorable); NS_ENSURE_SUCCESS_VOID(rv); // Re-import state. @@ -1548,7 +1633,8 @@ class FullscreenTransitionData : public nsISupports { public: NS_DECL_ISUPPORTS - explicit FullscreenTransitionData(NSWindow* aWindow) : mTransitionWindow(aWindow) {} + explicit FullscreenTransitionData(NSWindow* aWindow) + : mTransitionWindow(aWindow) {} NSWindow* mTransitionWindow; @@ -1586,10 +1672,12 @@ NS_IMPL_ISUPPORTS0(FullscreenTransitionData) @end static bool AlwaysUsesNativeFullScreen() { - return Preferences::GetBool("full-screen-api.macos-native-full-screen", false); + return Preferences::GetBool("full-screen-api.macos-native-full-screen", + false); } -/* virtual */ bool nsCocoaWindow::PrepareForFullscreenTransition(nsISupports** aData) { +/* virtual */ bool nsCocoaWindow::PrepareForFullscreenTransition( + nsISupports** aData) { if (AlwaysUsesNativeFullScreen()) { return false; } @@ -1607,10 +1695,11 @@ static bool AlwaysUsesNativeFullScreen() { nsCOMPtr widgetScreen = GetWidgetScreen(); NSScreen* cocoaScreen = ScreenHelperCocoa::CocoaScreenForScreen(widgetScreen); - NSWindow* win = [[NSWindow alloc] initWithContentRect:[cocoaScreen frame] - styleMask:NSWindowStyleMaskBorderless - backing:NSBackingStoreBuffered - defer:YES]; + NSWindow* win = + [[NSWindow alloc] initWithContentRect:[cocoaScreen frame] + styleMask:NSWindowStyleMaskBorderless + backing:NSBackingStoreBuffered + defer:YES]; [win setBackgroundColor:[NSColor blackColor]]; [win setAlphaValue:0]; [win setIgnoresMouseEvents:YES]; @@ -1628,12 +1717,12 @@ static bool AlwaysUsesNativeFullScreen() { mIgnoreOcclusionCount--; } -/* virtual */ void nsCocoaWindow::PerformFullscreenTransition(FullscreenTransitionStage aStage, - uint16_t aDuration, - nsISupports* aData, - nsIRunnable* aCallback) { +/* virtual */ void nsCocoaWindow::PerformFullscreenTransition( + FullscreenTransitionStage aStage, uint16_t aDuration, nsISupports* aData, + nsIRunnable* aCallback) { auto data = static_cast(aData); - FullscreenTransitionDelegate* delegate = [[FullscreenTransitionDelegate alloc] init]; + FullscreenTransitionDelegate* delegate = + [[FullscreenTransitionDelegate alloc] init]; delegate->mWindow = this; // Storing already_AddRefed directly could cause static checking fail. delegate->mCallback = nsCOMPtr(aCallback).forget().take(); @@ -1645,10 +1734,12 @@ static bool AlwaysUsesNativeFullScreen() { NSDictionary* dict = @{ NSViewAnimationTargetKey : data->mTransitionWindow, - NSViewAnimationEffectKey : aStage == eBeforeFullscreenToggle ? NSViewAnimationFadeInEffect - : NSViewAnimationFadeOutEffect + NSViewAnimationEffectKey : aStage == eBeforeFullscreenToggle + ? NSViewAnimationFadeInEffect + : NSViewAnimationFadeOutEffect }; - mFullscreenTransitionAnimation = [[NSViewAnimation alloc] initWithViewAnimations:@[ dict ]]; + mFullscreenTransitionAnimation = + [[NSViewAnimation alloc] initWithViewAnimations:@[ dict ]]; [mFullscreenTransitionAnimation setDelegate:delegate]; [mFullscreenTransitionAnimation setDuration:aDuration / 1000.0]; [mFullscreenTransitionAnimation startAnimation]; @@ -1659,8 +1750,8 @@ void nsCocoaWindow::CocoaWindowWillEnterFullscreen(bool aFullscreen) { mHasStartedNativeFullscreen = true; - // Ensure that we update our fullscreen state as early as possible, when the resize - // happens. + // Ensure that we update our fullscreen state as early as possible, when the + // resize happens. mUpdateFullscreenOnResize = Some(aFullscreen ? TransitionType::Fullscreen : TransitionType::Windowed); } @@ -1679,14 +1770,15 @@ void nsCocoaWindow::CocoaWindowDidFailFullscreen(bool aAttemptedFullscreen) { EndOurNativeTransition(); DispatchOcclusionEvent(); - // If we already updated our fullscreen state due to a resize, we need to update it again. + // If we already updated our fullscreen state due to a resize, we need to + // update it again. if (mUpdateFullscreenOnResize.isNothing()) { UpdateFullscreenState(!aAttemptedFullscreen, true); ReportSizeEvent(); } - TransitionType transition = - aAttemptedFullscreen ? TransitionType::Fullscreen : TransitionType::Windowed; + TransitionType transition = aAttemptedFullscreen ? TransitionType::Fullscreen + : TransitionType::Windowed; FinishCurrentTransitionIfMatching(transition); } @@ -1704,7 +1796,8 @@ void nsCocoaWindow::UpdateFullscreenState(bool aFullScreen, bool aNativeMode) { DispatchSizeModeEvent(); // Notify the mainChildView with our new fullscreen state. - nsChildView* mainChildView = static_cast([[mWindow mainChildView] widget]); + nsChildView* mainChildView = + static_cast([[mWindow mainChildView] widget]); if (mainChildView) { mainChildView->UpdateFullscreen(aFullScreen); } @@ -1718,7 +1811,8 @@ nsresult nsCocoaWindow::MakeFullScreenWithNativeTransition(bool aFullScreen) { return DoMakeFullScreen(aFullScreen, true); } -nsresult nsCocoaWindow::DoMakeFullScreen(bool aFullScreen, bool aUseSystemTransition) { +nsresult nsCocoaWindow::DoMakeFullScreen(bool aFullScreen, + bool aUseSystemTransition) { if (!mWindow) { return NS_OK; } @@ -1727,10 +1821,11 @@ nsresult nsCocoaWindow::DoMakeFullScreen(bool aFullScreen, bool aUseSystemTransi TransitionType transition = TransitionType::Windowed; if (aFullScreen) { // Decide whether to use fullscreen or emulated fullscreen. - transition = (aUseSystemTransition && - (mWindow.collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary)) - ? TransitionType::Fullscreen - : TransitionType::EmulatedFullscreen; + transition = + (aUseSystemTransition && (mWindow.collectionBehavior & + NSWindowCollectionBehaviorFullScreenPrimary)) + ? TransitionType::Fullscreen + : TransitionType::EmulatedFullscreen; } QueueTransition(transition); @@ -1757,11 +1852,12 @@ void nsCocoaWindow::ProcessTransitions() { while (!mTransitionsPending.empty() && !IsInTransition()) { TransitionType nextTransition = mTransitionsPending.front(); - // We have to check for some incompatible transition states, and if we find one, - // instead perform an alternative transition and leave the queue untouched. If - // we add one of these transitions, we set mIsTransitionCurrentAdded because we - // don't want to confuse listeners who are expecting to receive exactly one - // event when the requested transition has completed. + // We have to check for some incompatible transition states, and if we find + // one, instead perform an alternative transition and leave the queue + // untouched. If we add one of these transitions, we set + // mIsTransitionCurrentAdded because we don't want to confuse listeners who + // are expecting to receive exactly one event when the requested transition + // has completed. switch (nextTransition) { case TransitionType::Fullscreen: case TransitionType::EmulatedFullscreen: @@ -1784,8 +1880,8 @@ void nsCocoaWindow::ProcessTransitions() { break; } - // If mTransitionCurrent is still empty, then we use the nextTransition and pop - // the queue. + // If mTransitionCurrent is still empty, then we use the nextTransition and + // pop the queue. if (mTransitionCurrent.isNothing()) { mTransitionCurrent = Some(nextTransition); mTransitionsPending.pop(); @@ -1796,13 +1892,14 @@ void nsCocoaWindow::ProcessTransitions() { if (!mInFullScreenMode) { // Check our global state to see if it is safe to start a native // fullscreen transition. While that is false, run our own event loop. - // Eventually, the native fullscreen transition will finish, and we can - // safely continue. + // Eventually, the native fullscreen transition will finish, and we + // can safely continue. NSRunLoop* localRunLoop = [NSRunLoop currentRunLoop]; while (mWindow && !CanStartNativeTransition() && - [localRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) { - // This loop continues to process events until CanStartNativeTransition() - // returns true. + [localRunLoop runMode:NSDefaultRunLoopMode + beforeDate:[NSDate distantFuture]]) { + // This loop continues to process events until + // CanStartNativeTransition() returns true. } // This triggers an async animation, so continue. @@ -1816,9 +1913,9 @@ void nsCocoaWindow::ProcessTransitions() { if (!mInFullScreenMode) { NSDisableScreenUpdates(); mSuppressSizeModeEvents = true; - // The order here matters. When we exit full screen mode, we need to show the - // Dock first, otherwise the newly-created window won't have its minimize - // button enabled. See bug 526282. + // The order here matters. When we exit full screen mode, we need to + // show the Dock first, otherwise the newly-created window won't have + // its minimize button enabled. See bug 526282. nsCocoaUtils::HideOSChromeOnScreen(true); nsBaseWidget::InfallibleMakeFullScreen(true); mSuppressSizeModeEvents = false; @@ -1832,14 +1929,15 @@ void nsCocoaWindow::ProcessTransitions() { if (mInFullScreenMode) { if (mInNativeFullScreenMode) { // Check our global state to see if it is safe to start a native - // fullscreen transition. While that is false, run our own event loop. - // Eventually, the native fullscreen transition will finish, and we can - // safely continue. + // fullscreen transition. While that is false, run our own event + // loop. Eventually, the native fullscreen transition will finish, + // and we can safely continue. NSRunLoop* localRunLoop = [NSRunLoop currentRunLoop]; while (mWindow && !CanStartNativeTransition() && - [localRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) { - // This loop continues to process events until CanStartNativeTransition() - // returns true. + [localRunLoop runMode:NSDefaultRunLoopMode + beforeDate:[NSDate distantFuture]]) { + // This loop continues to process events until + // CanStartNativeTransition() returns true. } // This triggers an async animation, so continue. @@ -1848,9 +1946,9 @@ void nsCocoaWindow::ProcessTransitions() { } else { NSDisableScreenUpdates(); mSuppressSizeModeEvents = true; - // The order here matters. When we exit full screen mode, we need to show the - // Dock first, otherwise the newly-created window won't have its minimize - // button enabled. See bug 526282. + // The order here matters. When we exit full screen mode, we need to + // show the Dock first, otherwise the newly-created window won't + // have its minimize button enabled. See bug 526282. nsCocoaUtils::HideOSChromeOnScreen(false); nsBaseWidget::InfallibleMakeFullScreen(false); mSuppressSizeModeEvents = false; @@ -1860,17 +1958,19 @@ void nsCocoaWindow::ProcessTransitions() { } else if (mWindow.zoomed) { [mWindow zoom:nil]; - // Check if we're still zoomed. If we are, we need to do *something* to make the - // window smaller than the zoom size so Cocoa will treat us as being out of the - // zoomed state. Otherwise, we could stay zoomed and never be able to be "normal" - // from calls to SetSizeMode. + // Check if we're still zoomed. If we are, we need to do *something* + // to make the window smaller than the zoom size so Cocoa will treat + // us as being out of the zoomed state. Otherwise, we could stay + // zoomed and never be able to be "normal" from calls to SetSizeMode. if (mWindow.zoomed) { NSRect maximumFrame = mWindow.frame; const CGFloat INSET_OUT_OF_ZOOM = 20.0f; - [mWindow setFrame:NSInsetRect(maximumFrame, INSET_OUT_OF_ZOOM, INSET_OUT_OF_ZOOM) + [mWindow setFrame:NSInsetRect(maximumFrame, INSET_OUT_OF_ZOOM, + INSET_OUT_OF_ZOOM) display:YES]; - MOZ_ASSERT(!mWindow.zoomed, - "We should be able to unzoom by shrinking the frame a bit."); + MOZ_ASSERT( + !mWindow.zoomed, + "We should be able to unzoom by shrinking the frame a bit."); } } break; @@ -1908,10 +2008,11 @@ void nsCocoaWindow::ProcessTransitions() { mInProcessTransitions = false; - // When we finish processing transitions, dispatch a size mode event to cover the - // cases where an inserted transition suppressed one, and the original transition - // never sent one because it detected it was at the desired state when it ran. If - // we've already sent a size mode event, then this will be a no-op. + // When we finish processing transitions, dispatch a size mode event to cover + // the cases where an inserted transition suppressed one, and the original + // transition never sent one because it detected it was at the desired state + // when it ran. If we've already sent a size mode event, then this will be a + // no-op. if (!IsInTransition()) { DispatchSizeModeEvent(); } @@ -1925,24 +2026,26 @@ void nsCocoaWindow::FinishCurrentTransition() { ProcessTransitions(); } -void nsCocoaWindow::FinishCurrentTransitionIfMatching(const TransitionType& aTransition) { - // We've just finished some transition activity, and we're not sure whether it was - // triggered programmatically, or by the user. If it matches our current transition, - // then assume it was triggered programmatically and we can clean up that transition - // and start processing transitions again. +void nsCocoaWindow::FinishCurrentTransitionIfMatching( + const TransitionType& aTransition) { + // We've just finished some transition activity, and we're not sure whether it + // was triggered programmatically, or by the user. If it matches our current + // transition, then assume it was triggered programmatically and we can clean + // up that transition and start processing transitions again. // Whether programmatic or user-initiated, we send out a size mode event. DispatchSizeModeEvent(); if (mTransitionCurrent.isSome() && (*mTransitionCurrent == aTransition)) { // This matches our current transition. Since this function is called from - // nsWindowDelegate transition callbacks, we want to make sure those callbacks are - // all the way done before we start processing more transitions. To accomplish this, - // we dispatch our cleanup to happen on the next event loop. Doing this will ensure - // that any async native transition methods we call (like toggleFullScreen) will - // succeed. - NS_DispatchToCurrentThread(NewRunnableMethod("FinishCurrentTransition", this, - &nsCocoaWindow::FinishCurrentTransition)); + // nsWindowDelegate transition callbacks, we want to make sure those + // callbacks are all the way done before we start processing more + // transitions. To accomplish this, we dispatch our cleanup to happen on the + // next event loop. Doing this will ensure that any async native transition + // methods we call (like toggleFullScreen) will succeed. + NS_DispatchToCurrentThread( + NewRunnableMethod("FinishCurrentTransition", this, + &nsCocoaWindow::FinishCurrentTransition)); } } @@ -1951,21 +2054,22 @@ bool nsCocoaWindow::HandleUpdateFullscreenOnResize() { return false; } - bool toFullscreen = (*mUpdateFullscreenOnResize == TransitionType::Fullscreen); + bool toFullscreen = + (*mUpdateFullscreenOnResize == TransitionType::Fullscreen); mUpdateFullscreenOnResize.reset(); UpdateFullscreenState(toFullscreen, true); return true; } -/* static */ mozilla::StaticDataMutex nsCocoaWindow::sWindowInNativeTransition( - nullptr); +/* static */ mozilla::StaticDataMutex + nsCocoaWindow::sWindowInNativeTransition(nullptr); bool nsCocoaWindow::CanStartNativeTransition() { auto window = sWindowInNativeTransition.Lock(); if (*window == nullptr) { - // Claim it and return true, indicating that the caller has permission to start - // the native fullscreen transition. + // Claim it and return true, indicating that the caller has permission to + // start the native fullscreen transition. *window = this; return true; } @@ -1985,7 +2089,8 @@ void nsCocoaWindow::EndOurNativeTransition() { } // Coordinates are desktop pixels -void nsCocoaWindow::DoResize(double aX, double aY, double aWidth, double aHeight, bool aRepaint, +void nsCocoaWindow::DoResize(double aX, double aY, double aWidth, + double aHeight, bool aRepaint, bool aConstrainToCurrentScreen) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -2014,24 +2119,27 @@ void nsCocoaWindow::DoResize(double aX, double aY, double aWidth, double aHeight int32_t width = NSToIntRound(aWidth * scale); int32_t height = NSToIntRound(aHeight * scale); - width = - std::max(mSizeConstraints.mMinSize.width, std::min(mSizeConstraints.mMaxSize.width, width)); + width = std::max(mSizeConstraints.mMinSize.width, + std::min(mSizeConstraints.mMaxSize.width, width)); height = std::max(mSizeConstraints.mMinSize.height, std::min(mSizeConstraints.mMaxSize.height, height)); - DesktopIntRect newBounds(NSToIntRound(aX), NSToIntRound(aY), NSToIntRound(width / scale), + DesktopIntRect newBounds(NSToIntRound(aX), NSToIntRound(aY), + NSToIntRound(width / scale), NSToIntRound(height / scale)); // constrain to the screen that contains the largest area of the new rect - FitRectToVisibleAreaForScreen(newBounds, aConstrainToCurrentScreen ? [mWindow screen] : nullptr); + FitRectToVisibleAreaForScreen( + newBounds, aConstrainToCurrentScreen ? [mWindow screen] : nullptr); // convert requested bounds into Cocoa coordinate system NSRect newFrame = nsCocoaUtils::GeckoRectToCocoaRect(newBounds); NSRect frame = [mWindow frame]; - BOOL isMoving = newFrame.origin.x != frame.origin.x || newFrame.origin.y != frame.origin.y; - BOOL isResizing = - newFrame.size.width != frame.size.width || newFrame.size.height != frame.size.height; + BOOL isMoving = newFrame.origin.x != frame.origin.x || + newFrame.origin.y != frame.origin.y; + BOOL isResizing = newFrame.size.width != frame.size.width || + newFrame.size.height != frame.size.height; if (!isMoving && !isResizing) { return; @@ -2046,14 +2154,16 @@ void nsCocoaWindow::DoResize(double aX, double aY, double aWidth, double aHeight } // Coordinates are desktop pixels -void nsCocoaWindow::Resize(double aX, double aY, double aWidth, double aHeight, bool aRepaint) { +void nsCocoaWindow::Resize(double aX, double aY, double aWidth, double aHeight, + bool aRepaint) { DoResize(aX, aY, aWidth, aHeight, aRepaint, false); } // Coordinates are desktop pixels void nsCocoaWindow::Resize(double aWidth, double aHeight, bool aRepaint) { double invScale = 1.0 / BackingScaleFactor(); - DoResize(mBounds.x * invScale, mBounds.y * invScale, aWidth, aHeight, aRepaint, true); + DoResize(mBounds.x * invScale, mBounds.y * invScale, aWidth, aHeight, + aRepaint, true); } // Return the area that the Gecko ChildView in our window should cover, as an @@ -2071,7 +2181,8 @@ LayoutDeviceIntRect nsCocoaWindow::GetClientBounds() { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; CGFloat scaleFactor = BackingScaleFactor(); - return nsCocoaUtils::CocoaRectToGeckoRectDevPix(GetClientCocoaRect(), scaleFactor); + return nsCocoaUtils::CocoaRectToGeckoRectDevPix(GetClientCocoaRect(), + scaleFactor); NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntRect(0, 0, 0, 0)); } @@ -2081,7 +2192,8 @@ void nsCocoaWindow::UpdateBounds() { if (mWindow) { frame = [mWindow frame]; } - mBounds = nsCocoaUtils::CocoaRectToGeckoRectDevPix(frame, BackingScaleFactor()); + mBounds = + nsCocoaUtils::CocoaRectToGeckoRectDevPix(frame, BackingScaleFactor()); if (mPopupContentView) { mPopupContentView->UpdateBoundsFromView(); @@ -2092,8 +2204,8 @@ LayoutDeviceIntRect nsCocoaWindow::GetScreenBounds() { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; #ifdef DEBUG - LayoutDeviceIntRect r = - nsCocoaUtils::CocoaRectToGeckoRectDevPix([mWindow frame], BackingScaleFactor()); + LayoutDeviceIntRect r = nsCocoaUtils::CocoaRectToGeckoRectDevPix( + [mWindow frame], BackingScaleFactor()); NS_ASSERTION(mWindow && mBounds == r, "mBounds out of sync!"); #endif @@ -2142,7 +2254,8 @@ static CGFloat GetBackingScaleFactor(NSWindow* aWindow) { } // Then identify the screen it belongs to, and return its scale factor. - NSScreen* screen = FindTargetScreenForRect(nsCocoaUtils::CocoaRectToGeckoRect(frame)); + NSScreen* screen = + FindTargetScreenForRect(nsCocoaUtils::CocoaRectToGeckoRect(frame)); return nsCocoaUtils::GetBackingScaleFactor(screen); } @@ -2200,7 +2313,8 @@ nsresult nsCocoaWindow::SetTitle(const nsAString& aTitle) { const nsString& strTitle = PromiseFlatString(aTitle); const unichar* uniTitle = reinterpret_cast(strTitle.get()); - NSString* title = [NSString stringWithCharacters:uniTitle length:strTitle.Length()]; + NSString* title = [NSString stringWithCharacters:uniTitle + length:strTitle.Length()]; if ([mWindow drawsContentsIntoWindowFrame] && ![mWindow wantsTitleDrawn]) { // Don't cause invalidations when the title isn't displayed. [mWindow disableSetNeedsDisplay]; @@ -2228,7 +2342,8 @@ void nsCocoaWindow::Invalidate(const LayoutDeviceIntRect& aRect) { // a drop, to a drag enter/leave, or a drag over event. The actual event // is passed in |aMessage| and is passed along to our event hanlder so Gecko // knows about it. -bool nsCocoaWindow::DragEvent(unsigned int aMessage, mozilla::gfx::Point aMouseGlobal, +bool nsCocoaWindow::DragEvent(unsigned int aMessage, + mozilla::gfx::Point aMouseGlobal, UInt16 aKeyModifiers) { return false; } @@ -2237,7 +2352,8 @@ NS_IMETHODIMP nsCocoaWindow::SendSetZLevelEvent() { nsWindowZ placement = nsWindowZTop; nsCOMPtr actualBelow; if (mWidgetListener) - mWidgetListener->ZLevelChanged(true, &placement, nullptr, getter_AddRefs(actualBelow)); + mWidgetListener->ZLevelChanged(true, &placement, nullptr, + getter_AddRefs(actualBelow)); return NS_OK; } @@ -2248,8 +2364,9 @@ NS_IMETHODIMP nsCocoaWindow::GetChildSheet(bool aShown, nsIWidget** _retval) { if (child->GetWindowType() == WindowType::Sheet) { // if it's a sheet, it must be an nsCocoaWindow nsCocoaWindow* cocoaWindow = static_cast(child); - if (cocoaWindow->mWindow && ((aShown && [cocoaWindow->mWindow isVisible]) || - (!aShown && cocoaWindow->mSheetNeedsShow))) { + if (cocoaWindow->mWindow && + ((aShown && [cocoaWindow->mWindow isVisible]) || + (!aShown && cocoaWindow->mSheetNeedsShow))) { nsCOMPtr widget = cocoaWindow; widget.forget(_retval); return NS_OK; @@ -2273,27 +2390,30 @@ NS_IMETHODIMP nsCocoaWindow::GetIsSheet(bool* isSheet) { return NS_OK; } -NS_IMETHODIMP nsCocoaWindow::GetSheetWindowParent(NSWindow** sheetWindowParent) { +NS_IMETHODIMP nsCocoaWindow::GetSheetWindowParent( + NSWindow** sheetWindowParent) { *sheetWindowParent = mSheetWindowParent; return NS_OK; } // Invokes callback and ProcessEvent methods on Event Listener object -nsresult nsCocoaWindow::DispatchEvent(WidgetGUIEvent* event, nsEventStatus& aStatus) { +nsresult nsCocoaWindow::DispatchEvent(WidgetGUIEvent* event, + nsEventStatus& aStatus) { aStatus = nsEventStatus_eIgnore; nsCOMPtr kungFuDeathGrip(event->mWidget); mozilla::Unused << kungFuDeathGrip; // Not used within this function - if (mWidgetListener) aStatus = mWidgetListener->HandleEvent(event, mUseAttachedEvents); + if (mWidgetListener) + aStatus = mWidgetListener->HandleEvent(event, mUseAttachedEvents); return NS_OK; } -// aFullScreen should be the window's mInFullScreenMode. We don't have access to that -// from here, so we need to pass it in. mInFullScreenMode should be the canonical -// indicator that a window is currently full screen and it makes sense to keep -// all sizemode logic here. +// aFullScreen should be the window's mInFullScreenMode. We don't have access to +// that from here, so we need to pass it in. mInFullScreenMode should be the +// canonical indicator that a window is currently full screen and it makes sense +// to keep all sizemode logic here. static nsSizeMode GetWindowSizeMode(NSWindow* aWindow, bool aFullScreen) { if (aFullScreen) return nsSizeMode_Fullscreen; if ([aWindow isMiniaturized]) return nsSizeMode_Minimized; @@ -2358,9 +2478,11 @@ void nsCocoaWindow::DispatchOcclusionEvent() { // Our new occlusion state is true if the window is not visible. bool newOcclusionState = - !(mHasStartedNativeFullscreen || ([mWindow occlusionState] & NSWindowOcclusionStateVisible)); + !(mHasStartedNativeFullscreen || + ([mWindow occlusionState] & NSWindowOcclusionStateVisible)); - // Don't dispatch if the new occlustion state is the same as the current state. + // Don't dispatch if the new occlustion state is the same as the current + // state. if (mIsFullyOccluded == newOcclusionState) { return; } @@ -2398,19 +2520,22 @@ void nsCocoaWindow::SetMenuBar(RefPtr&& aMenuBar) { // Only paint for active windows, or paint the hidden window menu bar if no // other menu bar has been painted yet so that some reasonable menu bar is // displayed when the app starts up. - if (mMenuBar && ((!gSomeMenuBarPainted && nsMenuUtilsX::GetHiddenWindowMenuBar() == mMenuBar) || + if (mMenuBar && ((!gSomeMenuBarPainted && + nsMenuUtilsX::GetHiddenWindowMenuBar() == mMenuBar) || [mWindow isMainWindow])) mMenuBar->Paint(); } -void nsCocoaWindow::SetFocus(Raise aRaise, mozilla::dom::CallerType aCallerType) { +void nsCocoaWindow::SetFocus(Raise aRaise, + mozilla::dom::CallerType aCallerType) { if (!mWindow) return; if (mPopupContentView) { return mPopupContentView->SetFocus(aRaise, aCallerType); } - if (aRaise == Raise::Yes && ([mWindow isVisible] || [mWindow isMiniaturized])) { + if (aRaise == Raise::Yes && + ([mWindow isVisible] || [mWindow isMiniaturized])) { if ([mWindow isMiniaturized]) { [mWindow deminiaturize:nil]; } @@ -2423,7 +2548,8 @@ void nsCocoaWindow::SetFocus(Raise aRaise, mozilla::dom::CallerType aCallerType) LayoutDeviceIntPoint nsCocoaWindow::WidgetToScreenOffset() { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - return nsCocoaUtils::CocoaRectToGeckoRectDevPix(GetClientCocoaRect(), BackingScaleFactor()) + return nsCocoaUtils::CocoaRectToGeckoRectDevPix(GetClientCocoaRect(), + BackingScaleFactor()) .TopLeft(); NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntPoint(0, 0)); @@ -2442,7 +2568,8 @@ LayoutDeviceIntPoint nsCocoaWindow::GetClientOffset() { LayoutDeviceIntMargin nsCocoaWindow::ClientToWindowMargin() { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - if (!mWindow || mWindow.drawsContentsIntoWindowFrame || mWindowType == WindowType::Popup) { + if (!mWindow || mWindow.drawsContentsIntoWindowFrame || + mWindowType == WindowType::Popup) { return {}; } @@ -2450,8 +2577,10 @@ LayoutDeviceIntMargin nsCocoaWindow::ClientToWindowMargin() { NSRect frameNSRect = [mWindow frameRectForChildViewRect:clientNSRect]; CGFloat backingScale = BackingScaleFactor(); - const auto clientRect = nsCocoaUtils::CocoaRectToGeckoRectDevPix(clientNSRect, backingScale); - const auto frameRect = nsCocoaUtils::CocoaRectToGeckoRectDevPix(frameNSRect, backingScale); + const auto clientRect = + nsCocoaUtils::CocoaRectToGeckoRectDevPix(clientNSRect, backingScale); + const auto frameRect = + nsCocoaUtils::CocoaRectToGeckoRectDevPix(frameNSRect, backingScale); return frameRect - clientRect; @@ -2475,13 +2604,13 @@ void nsCocoaWindow::CaptureRollupEvents(bool aDoCapture) { // Sometimes more than one popup window can be visible at the same time // (e.g. nested non-native context menus, or the test case (attachment // 276885) for bmo bug 392389, which displays a non-native combo-box in a - // non-native popup window). In these cases the "active" popup window should - // be the topmost -- the (nested) context menu the mouse is currently over, - // or the combo-box's drop-down list (when it's displayed). But (among - // windows that have the same "level") OS X makes topmost the window that - // last received a mouse-down event, which may be incorrect (in the combo- - // box case, it makes topmost the window containing the combo-box). So - // here we fiddle with a non-native popup window's level to make sure the + // non-native popup window). In these cases the "active" popup window + // should be the topmost -- the (nested) context menu the mouse is currently + // over, or the combo-box's drop-down list (when it's displayed). But + // (among windows that have the same "level") OS X makes topmost the window + // that last received a mouse-down event, which may be incorrect (in the + // combo-box case, it makes topmost the window containing the combo-box). + // So here we fiddle with a non-native popup window's level to make sure the // "active" one is always above any other non-native popup windows that // may be visible. if (mWindow && (mWindowType == WindowType::Popup)) SetPopupWindowLevel(); @@ -2490,7 +2619,8 @@ void nsCocoaWindow::CaptureRollupEvents(bool aDoCapture) { // XXXndeakin this doesn't make sense. // Why is the new window assumed to be a modal panel? - if (mWindow && (mWindowType == WindowType::Popup)) [mWindow setLevel:NSModalPanelWindowLevel]; + if (mWindow && (mWindowType == WindowType::Popup)) + [mWindow setLevel:NSModalPanelWindowLevel]; } NS_OBJC_END_TRY_IGNORE_BLOCK; @@ -2505,7 +2635,9 @@ nsresult nsCocoaWindow::GetAttention(int32_t aCycleCount) { NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -bool nsCocoaWindow::HasPendingInputEvent() { return nsChildView::DoHasPendingInputEvent(); } +bool nsCocoaWindow::HasPendingInputEvent() { + return nsChildView::DoHasPendingInputEvent(); +} void nsCocoaWindow::SetWindowShadowStyle(StyleWindowShadow aStyle) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -2547,7 +2679,8 @@ void nsCocoaWindow::SetColorScheme(const Maybe& aScheme) { NS_OBJC_END_TRY_IGNORE_BLOCK; } -static inline CGAffineTransform GfxMatrixToCGAffineTransform(const gfx::Matrix& m) { +static inline CGAffineTransform GfxMatrixToCGAffineTransform( + const gfx::Matrix& m) { CGAffineTransform t; t.a = m._11; t.b = m._12; @@ -2606,7 +2739,8 @@ void nsCocoaWindow::SetWindowTransform(const gfx::Matrix& aTransform) { // and because the window server rounds down instead of to nearest. if (!transform.HasNonTranslation() && transform.HasNonIntegerTranslation()) { auto snappedTranslation = gfx::IntPoint::Round(transform.GetTranslation()); - transform = gfx::Matrix::Translation(snappedTranslation.x, snappedTranslation.y); + transform = + gfx::Matrix::Translation(snappedTranslation.x, snappedTranslation.y); } // We also need to account for the backing scale factor: aTransform is given @@ -2617,7 +2751,8 @@ void nsCocoaWindow::SetWindowTransform(const gfx::Matrix& aTransform) { transform.PostScale(1 / backingScale, 1 / backingScale); CGSConnection cid = _CGSDefaultConnection(); - CGSSetWindowTransform(cid, [mWindow windowNumber], GfxMatrixToCGAffineTransform(transform)); + CGSSetWindowTransform(cid, [mWindow windowNumber], + GfxMatrixToCGAffineTransform(transform)); mWindowTransformIsIdentity = isIdentity; @@ -2625,7 +2760,8 @@ void nsCocoaWindow::SetWindowTransform(const gfx::Matrix& aTransform) { } void nsCocoaWindow::SetInputRegion(const InputRegion& aInputRegion) { - MOZ_ASSERT(mWindowType == WindowType::Popup, "This should only be called on popup windows."); + MOZ_ASSERT(mWindowType == WindowType::Popup, + "This should only be called on popup windows."); // TODO: Somehow support aInputRegion.mMargin? Though maybe not. if (aInputRegion.mFullyTransparent) { [mWindow setIgnoresMouseEvents:YES]; @@ -2642,7 +2778,8 @@ void nsCocoaWindow::SetShowsToolbarButton(bool aShow) { NS_OBJC_END_TRY_IGNORE_BLOCK; } -void nsCocoaWindow::SetSupportsNativeFullscreen(bool aSupportsNativeFullscreen) { +void nsCocoaWindow::SetSupportsNativeFullscreen( + bool aSupportsNativeFullscreen) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; if (mWindow) { @@ -2664,7 +2801,8 @@ void nsCocoaWindow::SetSupportsNativeFullscreen(bool aSupportsNativeFullscreen) NS_OBJC_END_TRY_IGNORE_BLOCK; } -void nsCocoaWindow::SetWindowAnimationType(nsIWidget::WindowAnimationType aType) { +void nsCocoaWindow::SetWindowAnimationType( + nsIWidget::WindowAnimationType aType) { mAnimationType = aType; } @@ -2682,7 +2820,8 @@ void nsCocoaWindow::SetDrawsTitle(bool aDrawTitle) { NS_OBJC_END_TRY_IGNORE_BLOCK; } -nsresult nsCocoaWindow::SetNonClientMargins(const LayoutDeviceIntMargin& margins) { +nsresult nsCocoaWindow::SetNonClientMargins( + const LayoutDeviceIntMargin& margins) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; SetDrawsInTitlebar(margins.top == 0); @@ -2702,17 +2841,16 @@ void nsCocoaWindow::SetDrawsInTitlebar(bool aState) { NS_OBJC_END_TRY_IGNORE_BLOCK; } -NS_IMETHODIMP nsCocoaWindow::SynthesizeNativeMouseEvent(LayoutDeviceIntPoint aPoint, - NativeMouseMessage aNativeMessage, - MouseButton aButton, - nsIWidget::Modifiers aModifierFlags, - nsIObserver* aObserver) { +NS_IMETHODIMP nsCocoaWindow::SynthesizeNativeMouseEvent( + LayoutDeviceIntPoint aPoint, NativeMouseMessage aNativeMessage, + MouseButton aButton, nsIWidget::Modifiers aModifierFlags, + nsIObserver* aObserver) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; AutoObserverNotifier notifier(aObserver, "mouseevent"); if (mPopupContentView) { - return mPopupContentView->SynthesizeNativeMouseEvent(aPoint, aNativeMessage, aButton, - aModifierFlags, nullptr); + return mPopupContentView->SynthesizeNativeMouseEvent( + aPoint, aNativeMessage, aButton, aModifierFlags, nullptr); } return NS_OK; @@ -2721,17 +2859,18 @@ NS_IMETHODIMP nsCocoaWindow::SynthesizeNativeMouseEvent(LayoutDeviceIntPoint aPo } NS_IMETHODIMP nsCocoaWindow::SynthesizeNativeMouseScrollEvent( - LayoutDeviceIntPoint aPoint, uint32_t aNativeMessage, double aDeltaX, double aDeltaY, - double aDeltaZ, uint32_t aModifierFlags, uint32_t aAdditionalFlags, nsIObserver* aObserver) { + LayoutDeviceIntPoint aPoint, uint32_t aNativeMessage, double aDeltaX, + double aDeltaY, double aDeltaZ, uint32_t aModifierFlags, + uint32_t aAdditionalFlags, nsIObserver* aObserver) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; AutoObserverNotifier notifier(aObserver, "mousescrollevent"); if (mPopupContentView) { // Pass nullptr as the observer so that the AutoObserverNotification in // nsChildView::SynthesizeNativeMouseScrollEvent will be ignored. - return mPopupContentView->SynthesizeNativeMouseScrollEvent(aPoint, aNativeMessage, aDeltaX, - aDeltaY, aDeltaZ, aModifierFlags, - aAdditionalFlags, nullptr); + return mPopupContentView->SynthesizeNativeMouseScrollEvent( + aPoint, aNativeMessage, aDeltaX, aDeltaY, aDeltaZ, aModifierFlags, + aAdditionalFlags, nullptr); } return NS_OK; @@ -2746,9 +2885,11 @@ void nsCocoaWindow::LockAspectRatio(bool aShouldLock) { [mWindow setContentAspectRatio:mWindow.frame.size]; mAspectRatioLocked = true; } else { - // According to https://developer.apple.com/documentation/appkit/nswindow/1419507-aspectratio, - // aspect ratios and resize increments are mutually exclusive, and the accepted way of - // cancelling an established aspect ratio is to set the resize increments to 1.0, 1.0 + // According to + // https://developer.apple.com/documentation/appkit/nswindow/1419507-aspectratio, + // aspect ratios and resize increments are mutually exclusive, and the + // accepted way of cancelling an established aspect ratio is to set the + // resize increments to 1.0, 1.0 [mWindow setResizeIncrements:NSMakeSize(1.0, 1.0)]; mAspectRatioLocked = false; } @@ -2756,7 +2897,8 @@ void nsCocoaWindow::LockAspectRatio(bool aShouldLock) { NS_OBJC_END_TRY_IGNORE_BLOCK; } -void nsCocoaWindow::UpdateThemeGeometries(const nsTArray& aThemeGeometries) { +void nsCocoaWindow::UpdateThemeGeometries( + const nsTArray& aThemeGeometries) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; if (mPopupContentView) { @@ -2791,7 +2933,8 @@ void nsCocoaWindow::SetInputContext(const InputContext& aContext, NS_OBJC_END_TRY_IGNORE_BLOCK; } -bool nsCocoaWindow::GetEditCommands(NativeKeyBindingsType aType, const WidgetKeyboardEvent& aEvent, +bool nsCocoaWindow::GetEditCommands(NativeKeyBindingsType aType, + const WidgetKeyboardEvent& aEvent, nsTArray& aCommands) { // Validate the arguments. if (NS_WARN_IF(!nsIWidget::GetEditCommands(aType, aEvent, aCommands))) { @@ -2799,16 +2942,18 @@ bool nsCocoaWindow::GetEditCommands(NativeKeyBindingsType aType, const WidgetKey } NativeKeyBindings* keyBindings = NativeKeyBindings::GetInstance(aType); - // When the keyboard event is fired from this widget, it must mean that no web content has focus - // because any web contents should be on `nsChildView`. And in any locales, the system UI is - // always horizontal layout. So, let's pass `Nothing()` for the writing mode here, it won't be - // treated as in a vertical content. + // When the keyboard event is fired from this widget, it must mean that no web + // content has focus because any web contents should be on `nsChildView`. And + // in any locales, the system UI is always horizontal layout. So, let's pass + // `Nothing()` for the writing mode here, it won't be treated as in a vertical + // content. keyBindings->GetEditCommands(aEvent, Nothing(), aCommands); return true; } void nsCocoaWindow::PauseOrResumeCompositor(bool aPause) { - if (auto* mainChildView = static_cast([[mWindow mainChildView] widget])) { + if (auto* mainChildView = + static_cast([[mWindow mainChildView] widget])) { mainChildView->PauseOrResumeCompositor(aPause); } } @@ -2870,13 +3015,15 @@ already_AddRefed nsIWidget::CreateChildWindow() { if (!sApplicationMenu) return; NSMenu* mainMenu = [NSApp mainMenu]; - NS_ASSERTION([mainMenu numberOfItems] > 0, - "Main menu does not have any items, something is terribly wrong!"); + NS_ASSERTION( + [mainMenu numberOfItems] > 0, + "Main menu does not have any items, something is terribly wrong!"); // Create a new menu bar. - // We create a GeckoNSMenu because all menu bar NSMenu objects should use that subclass for - // key handling reasons. - GeckoNSMenu* newMenuBar = [[GeckoNSMenu alloc] initWithTitle:@"MainMenuBar"]; + // We create a GeckoNSMenu because all menu bar NSMenu objects should use + // that subclass for key handling reasons. + GeckoNSMenu* newMenuBar = + [[GeckoNSMenu alloc] initWithTitle:@"MainMenuBar"]; // move the application menu from the existing menu bar to the new one NSMenuItem* firstMenuItem = [[mainMenu itemAtIndex:0] retain]; @@ -2909,16 +3056,17 @@ already_AddRefed nsIWidget::CreateChildWindow() { return proposedFrameSize; } -- (NSRect)windowWillUseStandardFrame:(NSWindow*)window defaultFrame:(NSRect)newFrame { +- (NSRect)windowWillUseStandardFrame:(NSWindow*)window + defaultFrame:(NSRect)newFrame { // This function needs to return a rect representing the frame a window would - // have if it is in its "maximized" size mode. The parameter newFrame is supposed - // to be a frame representing the maximum window size on the screen where the - // window currently appears. However, in practice, newFrame can be a much smaller - // size. So, we ignore newframe and instead return the frame of the entire screen - // associated with the window. That frame is bigger than the window could actually - // be, due to the presence of the menubar and possibly the dock, but we never call - // this function directly, and Cocoa callers will shrink it to its true maximum - // size. + // have if it is in its "maximized" size mode. The parameter newFrame is + // supposed to be a frame representing the maximum window size on the screen + // where the window currently appears. However, in practice, newFrame can be a + // much smaller size. So, we ignore newframe and instead return the frame of + // the entire screen associated with the window. That frame is bigger than the + // window could actually be, due to the presence of the menubar and possibly + // the dock, but we never call this function directly, and Cocoa callers will + // shrink it to its true maximum size. return window.screen.frame; } @@ -3082,9 +3230,11 @@ void nsCocoaWindow::CocoaWindowDidResize() { // [NSApp _isRunningAppModal] will return true if we're running an OS dialog // app modally. If one of those is up then we want it to retain its menu bar. if ([NSApp _isRunningAppModal]) return; - RefPtr hiddenWindowMenuBar = nsMenuUtilsX::GetHiddenWindowMenuBar(); + RefPtr hiddenWindowMenuBar = + nsMenuUtilsX::GetHiddenWindowMenuBar(); if (hiddenWindowMenuBar) { - // printf("painting hidden window menu bar due to window losing main status\n"); + // printf("painting hidden window menu bar due to window losing main + // status\n"); hiddenWindowMenuBar->Paint(); } @@ -3126,7 +3276,8 @@ void nsCocoaWindow::CocoaWindowDidResize() { // If a sheet just resigned key then we should paint the menu bar // for whatever window is now main. NSWindow* window = [aNotification object]; - if ([window isSheet]) [WindowDelegate paintMenubarForWindow:[NSApp mainWindow]]; + if ([window isSheet]) + [WindowDelegate paintMenubarForWindow:[NSApp mainWindow]]; TextInputHandler::EnsureSecureEventInputDisabled(); @@ -3142,7 +3293,8 @@ void nsCocoaWindow::CocoaWindowDidResize() { } - (BOOL)windowShouldClose:(id)sender { - nsIWidgetListener* listener = mGeckoWindow ? mGeckoWindow->GetWidgetListener() : nullptr; + nsIWidgetListener* listener = + mGeckoWindow ? mGeckoWindow->GetWidgetListener() : nullptr; if (listener) listener->RequestWindowClose(mGeckoWindow); return NO; // gecko will do it } @@ -3159,14 +3311,16 @@ void nsCocoaWindow::CocoaWindowDidResize() { if (!mGeckoWindow) { return; } - mGeckoWindow->FinishCurrentTransitionIfMatching(nsCocoaWindow::TransitionType::Miniaturize); + mGeckoWindow->FinishCurrentTransitionIfMatching( + nsCocoaWindow::TransitionType::Miniaturize); } - (void)windowDidDeminiaturize:(NSNotification*)aNotification { if (!mGeckoWindow) { return; } - mGeckoWindow->FinishCurrentTransitionIfMatching(nsCocoaWindow::TransitionType::Deminiaturize); + mGeckoWindow->FinishCurrentTransitionIfMatching( + nsCocoaWindow::TransitionType::Deminiaturize); } - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)proposedFrame { @@ -3176,7 +3330,9 @@ void nsCocoaWindow::CocoaWindowDidResize() { return YES; } -- (NSRect)window:(NSWindow*)window willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect { +- (NSRect)window:(NSWindow*)window + willPositionSheet:(NSWindow*)sheet + usingRect:(NSRect)rect { if ([window isKindOfClass:[ToolbarWindow class]]) { rect.origin.y = [(ToolbarWindow*)window sheetAttachmentPosition]; } @@ -3184,7 +3340,9 @@ void nsCocoaWindow::CocoaWindowDidResize() { } #ifdef MOZ_THUNDERBIRD -- (void)didEndSheet:(NSWindow*)sheet returnCode:(int)returnCode contextInfo:(void*)contextInfo { +- (void)didEndSheet:(NSWindow*)sheet + returnCode:(int)returnCode + contextInfo:(void*)contextInfo { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; // Note: 'contextInfo' (if it is set) is the window that is the parent of @@ -3208,8 +3366,8 @@ void nsCocoaWindow::CocoaWindowDidResize() { NSWindow* window = (NSWindow*)[aNotification object]; if ([window respondsToSelector:@selector(backingScaleFactor)]) { - CGFloat oldFactor = - [[[aNotification userInfo] objectForKey:@"NSBackingPropertyOldScaleFactorKey"] doubleValue]; + CGFloat oldFactor = [[[aNotification userInfo] + objectForKey:@"NSBackingPropertyOldScaleFactorKey"] doubleValue]; if ([window backingScaleFactor] != oldFactor) { mGeckoWindow->BackingScaleFactorChanged(); } @@ -3262,7 +3420,8 @@ void nsCocoaWindow::CocoaWindowDidResize() { return self.FrameView__closeButtonOrigin; } ToolbarWindow* win = (ToolbarWindow*)[self window]; - if (win.drawsContentsIntoWindowFrame && !(win.styleMask & NSWindowStyleMaskFullScreen) && + if (win.drawsContentsIntoWindowFrame && + !(win.styleMask & NSWindowStyleMaskFullScreen) && (win.styleMask & NSWindowStyleMaskTitled)) { const NSRect buttonsRect = win.windowButtonsRect; if (NSIsEmptyRect(buttonsRect)) { @@ -3271,7 +3430,8 @@ void nsCocoaWindow::CocoaWindowDidResize() { // for the vertical coordinate will move the buttons above the window, // making them invisible. return NSMakePoint(buttonsRect.origin.x, win.frame.size.height); - } else if (win.windowTitlebarLayoutDirection == NSUserInterfaceLayoutDirectionRightToLeft) { + } else if (win.windowTitlebarLayoutDirection == + NSUserInterfaceLayoutDirectionRightToLeft) { // We're in RTL mode, which means that the close button is the rightmost // button of the three window buttons. and buttonsRect.origin is the // bottom left corner of the green (zoom) button. The close button is 40px @@ -3288,12 +3448,13 @@ void nsCocoaWindow::CocoaWindowDidResize() { CGFloat height = [self FrameView__titlebarHeight]; if ([[self window] isKindOfClass:[ToolbarWindow class]]) { // Make sure that the titlebar height includes our shifted buttons. - // The following coordinates are in window space, with the origin being at the bottom left - // corner of the window. + // The following coordinates are in window space, with the origin being at + // the bottom left corner of the window. ToolbarWindow* win = (ToolbarWindow*)[self window]; CGFloat frameHeight = [self frame].size.height; CGFloat windowButtonY = frameHeight; - if (!NSIsEmptyRect(win.windowButtonsRect) && win.drawsContentsIntoWindowFrame && + if (!NSIsEmptyRect(win.windowButtonsRect) && + win.drawsContentsIntoWindowFrame && !(win.styleMask & NSWindowStyleMaskFullScreen) && (win.styleMask & NSWindowStyleMaskTitled)) { windowButtonY = win.windowButtonsRect.origin.y; @@ -3339,10 +3500,10 @@ static NSMutableSet* gSwizzledFrameViewClasses = nil; } } - static IMP our_closeButtonOrigin = - class_getMethodImplementation([NSView class], @selector(FrameView__closeButtonOrigin)); - static IMP our_titlebarHeight = - class_getMethodImplementation([NSView class], @selector(FrameView__titlebarHeight)); + static IMP our_closeButtonOrigin = class_getMethodImplementation( + [NSView class], @selector(FrameView__closeButtonOrigin)); + static IMP our_titlebarHeight = class_getMethodImplementation( + [NSView class], @selector(FrameView__titlebarHeight)); if (![gSwizzledFrameViewClasses containsObject:frameViewClass]) { // Either of these methods might be implemented in both a subclass of @@ -3350,16 +3511,18 @@ static NSMutableSet* gSwizzledFrameViewClasses = nil; // aren't careful we might end up swizzling the same method twice. // Since method swizzling involves swapping pointers, this would break // things. - IMP _closeButtonOrigin = - class_getMethodImplementation(frameViewClass, @selector(_closeButtonOrigin)); + IMP _closeButtonOrigin = class_getMethodImplementation( + frameViewClass, @selector(_closeButtonOrigin)); if (_closeButtonOrigin && _closeButtonOrigin != our_closeButtonOrigin) { nsToolkit::SwizzleMethods(frameViewClass, @selector(_closeButtonOrigin), @selector(FrameView__closeButtonOrigin)); } - // Override _titlebarHeight so that the floating titlebar doesn't clip the bottom of the - // window buttons which we move down with our override of _closeButtonOrigin. - IMP _titlebarHeight = class_getMethodImplementation(frameViewClass, @selector(_titlebarHeight)); + // Override _titlebarHeight so that the floating titlebar doesn't clip the + // bottom of the window buttons which we move down with our override of + // _closeButtonOrigin. + IMP _titlebarHeight = class_getMethodImplementation( + frameViewClass, @selector(_titlebarHeight)); if (_titlebarHeight && _titlebarHeight != our_titlebarHeight) { nsToolkit::SwizzleMethods(frameViewClass, @selector(_titlebarHeight), @selector(FrameView__titlebarHeight)); @@ -3376,7 +3539,10 @@ static NSMutableSet* gSwizzledFrameViewClasses = nil; backing:(NSBackingStoreType)aBufferingType defer:(BOOL)aFlag { mDrawsIntoWindowFrame = NO; - [super initWithContentRect:aContentRect styleMask:aStyle backing:aBufferingType defer:aFlag]; + [super initWithContentRect:aContentRect + styleMask:aStyle + backing:aBufferingType + defer:aFlag]; mState = nil; mDisabledNeedsDisplay = NO; mTrackingArea = nil; @@ -3396,17 +3562,17 @@ static NSImage* GetMenuMaskImage() { CGFloat radius = 4.0f; NSEdgeInsets insets = {5, 5, 5, 5}; NSSize maskSize = {12, 12}; - NSImage* maskImage = [NSImage imageWithSize:maskSize - flipped:YES - drawingHandler:^BOOL(NSRect dstRect) { - NSBezierPath* path = - [NSBezierPath bezierPathWithRoundedRect:dstRect - xRadius:radius - yRadius:radius]; - [[NSColor colorWithDeviceWhite:1.0 alpha:1.0] set]; - [path fill]; - return YES; - }]; + NSImage* maskImage = [NSImage + imageWithSize:maskSize + flipped:YES + drawingHandler:^BOOL(NSRect dstRect) { + NSBezierPath* path = [NSBezierPath bezierPathWithRoundedRect:dstRect + xRadius:radius + yRadius:radius]; + [[NSColor colorWithDeviceWhite:1.0 alpha:1.0] set]; + [path fill]; + return YES; + }]; [maskImage setCapInsets:insets]; return maskImage; } @@ -3423,7 +3589,8 @@ static NSImage* GetMenuMaskImage() { - (void)setUseMenuStyle:(BOOL)aValue { if (aValue && !mUseMenuStyle) { // Turn on rounded corner masking. - NSView* effectView = VibrancyManager::CreateEffectView(VibrancyType::MENU, YES); + NSView* effectView = + VibrancyManager::CreateEffectView(VibrancyType::MENU, YES); [effectView setMaskImage:GetMenuMaskImage()]; [self swapOutChildViewWrapper:effectView]; [effectView release]; @@ -3481,7 +3648,8 @@ static NSImage* GetMenuMaskImage() { } static const NSString* kStateTitleKey = @"title"; -static const NSString* kStateDrawsContentsIntoWindowFrameKey = @"drawsContentsIntoWindowFrame"; +static const NSString* kStateDrawsContentsIntoWindowFrameKey = + @"drawsContentsIntoWindowFrame"; static const NSString* kStateShowsToolbarButton = @"showsToolbarButton"; static const NSString* kStateCollectionBehavior = @"collectionBehavior"; static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; @@ -3490,11 +3658,15 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; if (NSString* title = [aState objectForKey:kStateTitleKey]) { [self setTitle:title]; } - [self setDrawsContentsIntoWindowFrame:[[aState objectForKey:kStateDrawsContentsIntoWindowFrameKey] - boolValue]]; - [self setShowsToolbarButton:[[aState objectForKey:kStateShowsToolbarButton] boolValue]]; - [self setCollectionBehavior:[[aState objectForKey:kStateCollectionBehavior] unsignedIntValue]]; - [self setWantsTitleDrawn:[[aState objectForKey:kStateWantsTitleDrawn] boolValue]]; + [self setDrawsContentsIntoWindowFrame: + [[aState objectForKey:kStateDrawsContentsIntoWindowFrameKey] + boolValue]]; + [self setShowsToolbarButton:[[aState objectForKey:kStateShowsToolbarButton] + boolValue]]; + [self setCollectionBehavior:[[aState objectForKey:kStateCollectionBehavior] + unsignedIntValue]]; + [self setWantsTitleDrawn:[[aState objectForKey:kStateWantsTitleDrawn] + boolValue]]; } - (NSMutableDictionary*)exportState { @@ -3508,7 +3680,8 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; forKey:kStateShowsToolbarButton]; [state setObject:[NSNumber numberWithUnsignedInt:[self collectionBehavior]] forKey:kStateCollectionBehavior]; - [state setObject:[NSNumber numberWithBool:[self wantsTitleDrawn]] forKey:kStateWantsTitleDrawn]; + [state setObject:[NSNumber numberWithBool:[self wantsTitleDrawn]] + forKey:kStateWantsTitleDrawn]; return state; } @@ -3553,7 +3726,8 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; - (void)setWantsTitleDrawn:(BOOL)aDrawTitle { mDrawTitle = aDrawTitle; - [self setTitleVisibility:mDrawTitle ? NSWindowTitleVisible : NSWindowTitleHidden]; + [self setTitleVisibility:mDrawTitle ? NSWindowTitleVisible + : NSWindowTitleHidden]; } - (BOOL)wantsTitleDrawn { @@ -3590,8 +3764,9 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; [self removeTrackingArea]; NSView* view = [self trackingAreaView]; - const NSTrackingAreaOptions options = - NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways; + const NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | + NSTrackingMouseMoved | + NSTrackingActiveAlways; mTrackingArea = [[NSTrackingArea alloc] initWithRect:[view bounds] options:options owner:self @@ -3684,7 +3859,8 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; // We work around this problem by only returning AXChildren that are // mozAccessible object or are one of the titlebar's buttons (which // instantiate subclasses of NSButtonCell). - if ([retval isKindOfClass:[NSArray class]] && [attribute isEqualToString:@"AXChildren"]) { + if ([retval isKindOfClass:[NSArray class]] && + [attribute isEqualToString:@"AXChildren"]) { NSMutableArray* holder = [NSMutableArray arrayWithCapacity:10]; [holder addObjectsFromArray:(NSArray*)retval]; NSUInteger count = [holder count]; @@ -3725,11 +3901,12 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; self.material = NSVisualEffectMaterialTitlebar; self.blendingMode = NSVisualEffectBlendingModeWithinWindow; - // Add a separator line at the bottom of the titlebar. NSBoxSeparator isn't a perfect match for - // a native titlebar separator, but it's better than nothing. - // We really want the appearance that _NSTitlebarDecorationView creates with the help of CoreUI, - // but there's no public API for that. - NSBox* separatorLine = [[NSBox alloc] initWithFrame:NSMakeRect(0, 0, aFrame.size.width, 1)]; + // Add a separator line at the bottom of the titlebar. NSBoxSeparator isn't a + // perfect match for a native titlebar separator, but it's better than + // nothing. We really want the appearance that _NSTitlebarDecorationView + // creates with the help of CoreUI, but there's no public API for that. + NSBox* separatorLine = + [[NSBox alloc] initWithFrame:NSMakeRect(0, 0, aFrame.size.width, 1)]; separatorLine.autoresizingMask = NSViewWidthSizable | NSViewMaxYMargin; separatorLine.boxType = NSBoxSeparator; [self addSubview:separatorLine]; @@ -3744,9 +3921,10 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; - (void)mouseUp:(NSEvent*)event { if ([event clickCount] == 2) { - // Handle titlebar double click. We don't get the window's default behavior here because the - // window uses NSWindowStyleMaskFullSizeContentView, and this view (the titlebar gradient view) - // is technically part of the window "contents" (it's a subview of the content view). + // Handle titlebar double click. We don't get the window's default behavior + // here because the window uses NSWindowStyleMaskFullSizeContentView, and + // this view (the titlebar gradient view) is technically part of the window + // "contents" (it's a subview of the content view). if (nsCocoaUtils::ShouldZoomOnTitlebarDoubleClick()) { [[self window] performZoom:nil]; } else if (nsCocoaUtils::ShouldMinimizeOnTitlebarDoubleClick()) { @@ -3770,7 +3948,8 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; // NSWindows that this view is used in, including the floating full screen // toolbar window. The drawing bug was filed as FB9056136. See bug 1700211 // for more details. -#if !defined(MAC_OS_VERSION_11_0) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_VERSION_11_0 +#if !defined(MAC_OS_VERSION_11_0) || \ + MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_VERSION_11_0 if (nsCocoaFeatures::OnBigSurOrLater()) { #else if (@available(macOS 11.0, *)) { @@ -3784,7 +3963,8 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; @implementation FullscreenTitlebarTracker - (FullscreenTitlebarTracker*)init { [super init]; - self.view = [[[MOZTitlebarAccessoryView alloc] initWithFrame:NSZeroRect] autorelease]; + self.view = + [[[MOZTitlebarAccessoryView alloc] initWithFrame:NSZeroRect] autorelease]; self.hidden = YES; return self; } @@ -3818,9 +3998,9 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; // // The actual drawing of the gradient happens in two parts: The titlebar part // (i.e. the top 22 pixels of the gradient) is drawn by the MOZTitlebarView, -// which is a subview of the window's content view and a sibling of the ChildView. -// The rest of the gradient is drawn by Gecko into the ChildView, as part of the -// -moz-appearance rendering of the toolbar. +// which is a subview of the window's content view and a sibling of the +// ChildView. The rest of the gradient is drawn by Gecko into the ChildView, as +// part of the -moz-appearance rendering of the toolbar. @implementation ToolbarWindow - (id)initWithContentRect:(NSRect)aChildViewRect @@ -3832,17 +4012,20 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; // We treat aChildViewRect as the rectangle that the window's main ChildView // should be sized to. Get the right frameRect for the requested child view // rect. - NSRect frameRect = [NSWindow frameRectForContentRect:aChildViewRect styleMask:aStyle]; + NSRect frameRect = [NSWindow frameRectForContentRect:aChildViewRect + styleMask:aStyle]; // Always size the content view to the full frame size of the window. - // We do this even if we want this window to have a titlebar; in that case, the window's content - // view covers the entire window but the ChildView inside it will only cover the content area. We - // do this so that we can render the titlebar gradient manually, with a subview of our content - // view that's positioned in the titlebar area. This lets us have a smooth connection between - // titlebar and toolbar gradient in case the window has a "unified toolbar + titlebar" look. - // Moreover, always using a full size content view lets us toggle the titlebar on and off without - // changing the window's style mask (which would have other subtle effects, for example on - // keyboard focus). + // We do this even if we want this window to have a titlebar; in that case, + // the window's content view covers the entire window but the ChildView inside + // it will only cover the content area. We do this so that we can render the + // titlebar gradient manually, with a subview of our content view that's + // positioned in the titlebar area. This lets us have a smooth connection + // between titlebar and toolbar gradient in case the window has a "unified + // toolbar + titlebar" look. Moreover, always using a full size content view + // lets us toggle the titlebar on and off without changing the window's style + // mask (which would have other subtle effects, for example on keyboard + // focus). aStyle |= NSWindowStyleMaskFullSizeContentView; // -[NSWindow initWithContentRect:styleMask:backing:defer:] calls @@ -3863,7 +4046,8 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; mInitialTitlebarHeight = [self titlebarHeight]; [self setTitlebarAppearsTransparent:YES]; -#if !defined(MAC_OS_VERSION_11_0) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_VERSION_11_0 +#if !defined(MAC_OS_VERSION_11_0) || \ + MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_VERSION_11_0 if (nsCocoaFeatures::OnBigSurOrLater()) { #else if (@available(macOS 11.0, *)) { @@ -3882,7 +4066,8 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; context:nil]; // Adding this accessory view controller allows us to shift the toolbar down // when the user mouses to the top of the screen in fullscreen. - [(NSWindow*)self addTitlebarAccessoryViewController:mFullscreenTitlebarTracker]; + [(NSWindow*)self + addTitlebarAccessoryViewController:mFullscreenTitlebarTracker]; } return self; @@ -3898,14 +4083,18 @@ static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn"; NSNumber* revealAmount = (change[NSKeyValueChangeNewKey]); [self updateTitlebarShownAmount:[revealAmount doubleValue]]; } else { - [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + [super observeValueForKeyPath:keyPath + ofObject:object + change:change + context:context]; } } static bool ScreenHasNotch(nsCocoaWindow* aGeckoWindow) { if (@available(macOS 12.0, *)) { nsCOMPtr widgetScreen = aGeckoWindow->GetWidgetScreen(); - NSScreen* cocoaScreen = ScreenHelperCocoa::CocoaScreenForScreen(widgetScreen); + NSScreen* cocoaScreen = + ScreenHelperCocoa::CocoaScreenForScreen(widgetScreen); return cocoaScreen.safeAreaInsets.top != 0.0f; } return false; @@ -3965,8 +4154,8 @@ static bool ShouldShiftByMenubarHeightInFullscreen(nsCocoaWindow* aWindow) { // DesktopToLayoutDeviceScale in nsCocoaWindow. The latter accounts for // screen DPI. We don't want that because the revealAmount property // already accounts for it, so we'd be compounding DPI scales > 1. - mozilla::DesktopCoord coord = - LayoutDeviceCoord(shiftByPixels) / mozilla::DesktopToLayoutDeviceScale(); + mozilla::DesktopCoord coord = LayoutDeviceCoord(shiftByPixels) / + mozilla::DesktopToLayoutDeviceScale(); listener->MacFullscreenMenubarOverlapChanged(coord); } @@ -3983,7 +4172,8 @@ static bool ShouldShiftByMenubarHeightInFullscreen(nsCocoaWindow* aWindow) { } - (NSArray*)contentViewContents { - NSMutableArray* contents = [[[self contentView] subviews] mutableCopy]; + NSMutableArray* contents = + [[[self contentView] subviews] mutableCopy]; if (mTitlebarView) { // Do not include the titlebar gradient view in the returned array. [contents removeObject:mTitlebarView]; @@ -3992,11 +4182,15 @@ static bool ShouldShiftByMenubarHeightInFullscreen(nsCocoaWindow* aWindow) { } - (void)updateTitlebarView { - BOOL needTitlebarView = ![self drawsContentsIntoWindowFrame] || mUnifiedToolbarHeight > 0; + BOOL needTitlebarView = + ![self drawsContentsIntoWindowFrame] || mUnifiedToolbarHeight > 0; if (needTitlebarView && !mTitlebarView) { - mTitlebarView = [[MOZTitlebarView alloc] initWithFrame:[self unifiedToolbarRect]]; + mTitlebarView = + [[MOZTitlebarView alloc] initWithFrame:[self unifiedToolbarRect]]; mTitlebarView.autoresizingMask = NSViewWidthSizable | NSViewMinYMargin; - [self.contentView addSubview:mTitlebarView positioned:NSWindowBelow relativeTo:nil]; + [self.contentView addSubview:mTitlebarView + positioned:NSWindowBelow + relativeTo:nil]; } else if (needTitlebarView && mTitlebarView) { mTitlebarView.frame = [self unifiedToolbarRect]; } else if (!needTitlebarView && mTitlebarView) { @@ -4017,14 +4211,14 @@ static bool ShouldShiftByMenubarHeightInFullscreen(nsCocoaWindow* aWindow) { - (NSRect)titlebarRect { CGFloat titlebarHeight = [self titlebarHeight]; - return NSMakeRect(0, [self frame].size.height - titlebarHeight, [self frame].size.width, - titlebarHeight); + return NSMakeRect(0, [self frame].size.height - titlebarHeight, + [self frame].size.width, titlebarHeight); } // In window contentView coordinates (origin bottom left) - (NSRect)unifiedToolbarRect { - return NSMakeRect(0, [self frame].size.height - mUnifiedToolbarHeight, [self frame].size.width, - mUnifiedToolbarHeight); + return NSMakeRect(0, [self frame].size.height - mUnifiedToolbarHeight, + [self frame].size.width, mUnifiedToolbarHeight); } // Returns the unified height of titlebar + toolbar. @@ -4039,7 +4233,8 @@ static bool ShouldShiftByMenubarHeightInFullscreen(nsCocoaWindow* aWindow) { NSRect frameRect = [self frame]; NSUInteger styleMask = [self styleMask]; styleMask &= ~NSWindowStyleMaskFullSizeContentView; - NSRect originalContentRect = [NSWindow contentRectForFrameRect:frameRect styleMask:styleMask]; + NSRect originalContentRect = [NSWindow contentRectForFrameRect:frameRect + styleMask:styleMask]; return NSMaxY(frameRect) - NSMaxY(originalContentRect); } @@ -4165,7 +4360,9 @@ static bool ShouldShiftByMenubarHeightInFullscreen(nsCocoaWindow* aWindow) { if (delegate && [delegate isKindOfClass:[WindowDelegate class]]) { nsCocoaWindow* widget = [(WindowDelegate*)delegate geckoWidget]; if (widget) { - if (gGeckoAppModalWindowList && (widget != gGeckoAppModalWindowList->window)) return; + if (gGeckoAppModalWindowList && + (widget != gGeckoAppModalWindowList->window)) + return; if (widget->HasModalDescendents()) return; } } @@ -4279,7 +4476,9 @@ static const NSUInteger kWindowShadowOptionsTooltip = 4; if (delegate && [delegate isKindOfClass:[WindowDelegate class]]) { nsCocoaWindow* widget = [(WindowDelegate*)delegate geckoWidget]; if (widget) { - if (gGeckoAppModalWindowList && (widget != gGeckoAppModalWindowList->window)) return; + if (gGeckoAppModalWindowList && + (widget != gGeckoAppModalWindowList->window)) + return; if (widget->HasModalDescendents()) return; } } diff --git a/widget/cocoa/nsColorPicker.mm b/widget/cocoa/nsColorPicker.mm index 255610b27c07..366655777259 100644 --- a/widget/cocoa/nsColorPicker.mm +++ b/widget/cocoa/nsColorPicker.mm @@ -96,25 +96,30 @@ nsColorPicker::~nsColorPicker() { // TODO(bug 1805397): Implement default colors NS_IMETHODIMP nsColorPicker::Init(mozIDOMWindowProxy* aParent, const nsAString& aTitle, - const nsAString& aInitialColor, const nsTArray& aDefaultColors) { - MOZ_ASSERT(NS_IsMainThread(), "Color pickers can only be opened from main thread currently"); + const nsAString& aInitialColor, + const nsTArray& aDefaultColors) { + MOZ_ASSERT(NS_IsMainThread(), + "Color pickers can only be opened from main thread currently"); mTitle = aTitle; mColor = aInitialColor; mColorPanelWrapper = [[NSColorPanelWrapper alloc] initWithPicker:this]; return NS_OK; } -/* static */ NSColor* nsColorPicker::GetNSColorFromHexString(const nsAString& aColor) { +/* static */ NSColor* nsColorPicker::GetNSColorFromHexString( + const nsAString& aColor) { NSString* str = nsCocoaUtils::ToNSString(aColor); double red = HexStrToInt([str substringWithRange:NSMakeRange(1, 2)]) / 255.0; - double green = HexStrToInt([str substringWithRange:NSMakeRange(3, 2)]) / 255.0; + double green = + HexStrToInt([str substringWithRange:NSMakeRange(3, 2)]) / 255.0; double blue = HexStrToInt([str substringWithRange:NSMakeRange(5, 2)]) / 255.0; return [NSColor colorWithDeviceRed:red green:green blue:blue alpha:1.0]; } -/* static */ void nsColorPicker::GetHexStringFromNSColor(NSColor* aColor, nsAString& aResult) { +/* static */ void nsColorPicker::GetHexStringFromNSColor(NSColor* aColor, + nsAString& aResult) { CGFloat redFloat, greenFloat, blueFloat; NSColor* color = aColor; @@ -126,7 +131,8 @@ nsColorPicker::Init(mozIDOMWindowProxy* aParent, const nsAString& aTitle, } nsCocoaUtils::GetStringForNSString( - [NSString stringWithFormat:@"#%02x%02x%02x", (int)(redFloat * 255), (int)(greenFloat * 255), + [NSString stringWithFormat:@"#%02x%02x%02x", (int)(redFloat * 255), + (int)(greenFloat * 255), (int)(blueFloat * 255)], aResult); } @@ -136,7 +142,8 @@ nsColorPicker::Open(nsIColorPickerShownCallback* aCallback) { MOZ_ASSERT(aCallback); mCallback = aCallback; - [mColorPanelWrapper open:GetNSColorFromHexString(mColor) title:nsCocoaUtils::ToNSString(mTitle)]; + [mColorPanelWrapper open:GetNSColorFromHexString(mColor) + title:nsCocoaUtils::ToNSString(mTitle)]; NS_ADDREF_THIS(); diff --git a/widget/cocoa/nsCursorManager.mm b/widget/cocoa/nsCursorManager.mm index 6596df25a3b2..71cecd166d28 100644 --- a/widget/cocoa/nsCursorManager.mm +++ b/widget/cocoa/nsCursorManager.mm @@ -20,8 +20,8 @@ static constexpr nsCursor kCustomCursor = eCursorCount; /*! @method getCursor: @abstract Get a reference to the native Mac representation of a cursor. @discussion Gets a reference to the Mac native implementation of a cursor. - If the cursor has been requested before, it is retreived from the cursor cache, - otherwise it is created and cached. + If the cursor has been requested before, it is retreived from + the cursor cache, otherwise it is created and cached. @param aCursor the cursor to get @result the Mac native implementation of the cursor */ @@ -29,8 +29,9 @@ static constexpr nsCursor kCustomCursor = eCursorCount; /*! @method setMacCursor: @abstract Set the current Mac native cursor - @discussion Sets the current cursor - this routine is what actually causes the cursor to change. - The argument is retained and the old cursor is released. + @discussion Sets the current cursor - this routine is what actually causes the + cursor to change. The argument is retained and the old cursor is + released. @param aMacCursor the cursor to set @result NS_OK */ @@ -38,7 +39,8 @@ static constexpr nsCursor kCustomCursor = eCursorCount; /*! @method createCursor: @abstract Create a Mac native representation of a cursor. - @discussion Creates a version of the Mac native representation of this cursor + @discussion Creates a version of the Mac native representation of this + cursor. @param aCursor the cursor to create @result the Mac native implementation of the cursor */ @@ -76,92 +78,128 @@ static constexpr nsCursor kCustomCursor = eCursorCount; return [nsMacCursor cursorWithCursor:[NSCursor arrowCursor] type:aCursor]; case eCursor_wait: case eCursor_spinning: { - return [nsMacCursor cursorWithCursor:[NSCursor busyButClickableCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor busyButClickableCursor] + type:aCursor]; } case eCursor_select: return [nsMacCursor cursorWithCursor:[NSCursor IBeamCursor] type:aCursor]; case eCursor_hyperlink: - return [nsMacCursor cursorWithCursor:[NSCursor pointingHandCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor pointingHandCursor] + type:aCursor]; case eCursor_crosshair: - return [nsMacCursor cursorWithCursor:[NSCursor crosshairCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor crosshairCursor] + type:aCursor]; case eCursor_move: - return [nsMacCursor cursorWithImageNamed:@"move" hotSpot:NSMakePoint(12, 12) type:aCursor]; + return [nsMacCursor cursorWithImageNamed:@"move" + hotSpot:NSMakePoint(12, 12) + type:aCursor]; case eCursor_help: - return [nsMacCursor cursorWithImageNamed:@"help" hotSpot:NSMakePoint(12, 12) type:aCursor]; + return [nsMacCursor cursorWithImageNamed:@"help" + hotSpot:NSMakePoint(12, 12) + type:aCursor]; case eCursor_copy: { SEL cursorSelector = @selector(dragCopyCursor); - return [nsMacCursor cursorWithCursor:[NSCursor respondsToSelector:cursorSelector] - ? [NSCursor performSelector:cursorSelector] - : [NSCursor arrowCursor] - type:aCursor]; + return [nsMacCursor + cursorWithCursor:[NSCursor respondsToSelector:cursorSelector] + ? [NSCursor performSelector:cursorSelector] + : [NSCursor arrowCursor] + type:aCursor]; } case eCursor_alias: { SEL cursorSelector = @selector(dragLinkCursor); - return [nsMacCursor cursorWithCursor:[NSCursor respondsToSelector:cursorSelector] - ? [NSCursor performSelector:cursorSelector] - : [NSCursor arrowCursor] - type:aCursor]; + return [nsMacCursor + cursorWithCursor:[NSCursor respondsToSelector:cursorSelector] + ? [NSCursor performSelector:cursorSelector] + : [NSCursor arrowCursor] + type:aCursor]; } case eCursor_context_menu: { SEL cursorSelector = @selector(contextualMenuCursor); - return [nsMacCursor cursorWithCursor:[NSCursor respondsToSelector:cursorSelector] - ? [NSCursor performSelector:cursorSelector] - : [NSCursor arrowCursor] - type:aCursor]; + return [nsMacCursor + cursorWithCursor:[NSCursor respondsToSelector:cursorSelector] + ? [NSCursor performSelector:cursorSelector] + : [NSCursor arrowCursor] + type:aCursor]; } case eCursor_cell: - return [nsMacCursor cursorWithImageNamed:@"cell" hotSpot:NSMakePoint(12, 12) type:aCursor]; + return [nsMacCursor cursorWithImageNamed:@"cell" + hotSpot:NSMakePoint(12, 12) + type:aCursor]; case eCursor_grab: - return [nsMacCursor cursorWithCursor:[NSCursor openHandCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor openHandCursor] + type:aCursor]; case eCursor_grabbing: - return [nsMacCursor cursorWithCursor:[NSCursor closedHandCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor closedHandCursor] + type:aCursor]; case eCursor_zoom_in: - return [nsMacCursor cursorWithImageNamed:@"zoomIn" hotSpot:NSMakePoint(10, 10) type:aCursor]; + return [nsMacCursor cursorWithImageNamed:@"zoomIn" + hotSpot:NSMakePoint(10, 10) + type:aCursor]; case eCursor_zoom_out: - return [nsMacCursor cursorWithImageNamed:@"zoomOut" hotSpot:NSMakePoint(10, 10) type:aCursor]; + return [nsMacCursor cursorWithImageNamed:@"zoomOut" + hotSpot:NSMakePoint(10, 10) + type:aCursor]; case eCursor_vertical_text: - return [nsMacCursor cursorWithImageNamed:@"vtIBeam" hotSpot:NSMakePoint(12, 11) type:aCursor]; + return [nsMacCursor cursorWithImageNamed:@"vtIBeam" + hotSpot:NSMakePoint(12, 11) + type:aCursor]; case eCursor_all_scroll: - return [nsMacCursor cursorWithCursor:[NSCursor openHandCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor openHandCursor] + type:aCursor]; case eCursor_not_allowed: case eCursor_no_drop: { SEL cursorSelector = @selector(operationNotAllowedCursor); - return [nsMacCursor cursorWithCursor:[NSCursor respondsToSelector:cursorSelector] - ? [NSCursor performSelector:cursorSelector] - : [NSCursor arrowCursor] - type:aCursor]; + return [nsMacCursor + cursorWithCursor:[NSCursor respondsToSelector:cursorSelector] + ? [NSCursor performSelector:cursorSelector] + : [NSCursor arrowCursor] + type:aCursor]; } // Resize Cursors: // North case eCursor_n_resize: - return [nsMacCursor cursorWithCursor:[NSCursor resizeUpCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor resizeUpCursor] + type:aCursor]; // North East case eCursor_ne_resize: - return [nsMacCursor cursorWithImageNamed:@"sizeNE" hotSpot:NSMakePoint(12, 11) type:aCursor]; + return [nsMacCursor cursorWithImageNamed:@"sizeNE" + hotSpot:NSMakePoint(12, 11) + type:aCursor]; // East case eCursor_e_resize: - return [nsMacCursor cursorWithCursor:[NSCursor resizeRightCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor resizeRightCursor] + type:aCursor]; // South East case eCursor_se_resize: - return [nsMacCursor cursorWithImageNamed:@"sizeSE" hotSpot:NSMakePoint(12, 12) type:aCursor]; + return [nsMacCursor cursorWithImageNamed:@"sizeSE" + hotSpot:NSMakePoint(12, 12) + type:aCursor]; // South case eCursor_s_resize: - return [nsMacCursor cursorWithCursor:[NSCursor resizeDownCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor resizeDownCursor] + type:aCursor]; // South West case eCursor_sw_resize: - return [nsMacCursor cursorWithImageNamed:@"sizeSW" hotSpot:NSMakePoint(10, 12) type:aCursor]; + return [nsMacCursor cursorWithImageNamed:@"sizeSW" + hotSpot:NSMakePoint(10, 12) + type:aCursor]; // West case eCursor_w_resize: - return [nsMacCursor cursorWithCursor:[NSCursor resizeLeftCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor resizeLeftCursor] + type:aCursor]; // North West case eCursor_nw_resize: - return [nsMacCursor cursorWithImageNamed:@"sizeNW" hotSpot:NSMakePoint(11, 11) type:aCursor]; + return [nsMacCursor cursorWithImageNamed:@"sizeNW" + hotSpot:NSMakePoint(11, 11) + type:aCursor]; // North & South case eCursor_ns_resize: - return [nsMacCursor cursorWithCursor:[NSCursor resizeUpDownCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor resizeUpDownCursor] + type:aCursor]; // East & West case eCursor_ew_resize: - return [nsMacCursor cursorWithCursor:[NSCursor resizeLeftRightCursor] type:aCursor]; + return [nsMacCursor cursorWithCursor:[NSCursor resizeLeftRightCursor] + type:aCursor]; // North East & South West case eCursor_nesw_resize: return [nsMacCursor cursorWithImageNamed:@"sizeNESW" @@ -241,8 +279,10 @@ static constexpr nsCursor kCustomCursor = eCursorCount; widgetScaleFactor:(CGFloat)scaleFactor { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - // As the user moves the mouse, this gets called repeatedly with the same aCursorImage - if (sCurrentCursor == aCursor && sCurrentCursorScaleFactor == scaleFactor && mCurrentMacCursor) { + // As the user moves the mouse, this gets called repeatedly with the same + // aCursorImage + if (sCurrentCursor == aCursor && sCurrentCursorScaleFactor == scaleFactor && + mCurrentMacCursor) { // Native dragging can unset our cursor apparently (see bug 1739352). if (MOZ_UNLIKELY(![mCurrentMacCursor isSet])) { [mCurrentMacCursor set]; @@ -265,7 +305,8 @@ static constexpr nsCursor kCustomCursor = eCursorCount; NSImage* cursorImage; nsresult rv = nsCocoaUtils::CreateNSImageFromImageContainer( - aCursor.mContainer, imgIContainer::FRAME_FIRST, nullptr, nullptr, &cursorImage, scaleFactor); + aCursor.mContainer, imgIContainer::FRAME_FIRST, nullptr, nullptr, + &cursorImage, scaleFactor); if (NS_FAILED(rv) || !cursorImage) { return NS_ERROR_FAILURE; } @@ -277,11 +318,14 @@ static constexpr nsCursor kCustomCursor = eCursorCount; } // if the hotspot is nonsensical, make it 0,0 - uint32_t hotspotX = aCursor.mHotspotX > (uint32_t(size.width) - 1) ? 0 : aCursor.mHotspotX; - uint32_t hotspotY = aCursor.mHotspotY > (uint32_t(size.height) - 1) ? 0 : aCursor.mHotspotY; + uint32_t hotspotX = + aCursor.mHotspotX > (uint32_t(size.width) - 1) ? 0 : aCursor.mHotspotX; + uint32_t hotspotY = + aCursor.mHotspotY > (uint32_t(size.height) - 1) ? 0 : aCursor.mHotspotY; NSPoint hotSpot = ::NSMakePoint(hotspotX, hotspotY); - [self setMacCursor:[nsMacCursor cursorWithCursor:[[NSCursor alloc] initWithImage:cursorImage - hotSpot:hotSpot] + [self setMacCursor:[nsMacCursor cursorWithCursor:[[NSCursor alloc] + initWithImage:cursorImage + hotSpot:hotSpot] type:kCustomCursor]]; [cursorImage release]; return NS_OK; @@ -292,7 +336,8 @@ static constexpr nsCursor kCustomCursor = eCursorCount; - (nsMacCursor*)getCursor:(enum nsCursor)aCursor { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - nsMacCursor* result = [mCursors objectForKey:[NSNumber numberWithInt:aCursor]]; + nsMacCursor* result = + [mCursors objectForKey:[NSNumber numberWithInt:aCursor]]; if (!result) { result = [nsCursorManager createCursor:aCursor]; [mCursors setObject:result forKey:[NSNumber numberWithInt:aCursor]]; diff --git a/widget/cocoa/nsDeviceContextSpecX.mm b/widget/cocoa/nsDeviceContextSpecX.mm index 568eec44dccf..9bb8449b705e 100644 --- a/widget/cocoa/nsDeviceContextSpecX.mm +++ b/widget/cocoa/nsDeviceContextSpecX.mm @@ -67,7 +67,8 @@ nsDeviceContextSpecX::~nsDeviceContextSpecX() { NS_IMPL_ISUPPORTS(nsDeviceContextSpecX, nsIDeviceContextSpec) -NS_IMETHODIMP nsDeviceContextSpecX::Init(nsIPrintSettings* aPS, bool aIsPrintPreview) { +NS_IMETHODIMP nsDeviceContextSpecX::Init(nsIPrintSettings* aPS, + bool aIsPrintPreview) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; RefPtr settings(do_QueryObject(aPS)); @@ -81,7 +82,8 @@ NS_IMETHODIMP nsDeviceContextSpecX::Init(nsIPrintSettings* aPS, bool aIsPrintPre if (!printInfo) { return NS_ERROR_FAILURE; } - if (aPS->GetOutputDestination() == nsIPrintSettings::kOutputDestinationStream) { + if (aPS->GetOutputDestination() == + nsIPrintSettings::kOutputDestinationStream) { aPS->GetOutputStream(getter_AddRefs(mOutputStream)); if (!mOutputStream) { return NS_ERROR_FAILURE; @@ -108,17 +110,20 @@ NS_IMETHODIMP nsDeviceContextSpecX::Init(nsIPrintSettings* aPS, bool aIsPrintPre // TODO: Currently we do not support using SkPDF for kPMDestinationFax or // kPMDestinationProcessPDF ("Add PDF to iBooks, etc.), and we only support // it for kPMDestinationFile if the destination file is a PDF. - // XXX Could PMWorkflowSubmitPDFWithSettings/PMPrinterPrintWithProvider help? + // XXX Could PMWorkflowSubmitPDFWithSettings/PMPrinterPrintWithProvider + // help? OSStatus status = noErr; PMDestinationType destination; - status = ::PMSessionGetDestinationType(mPrintSession, mPMPrintSettings, &destination); + status = ::PMSessionGetDestinationType(mPrintSession, mPMPrintSettings, + &destination); if (status == noErr) { - if (destination == kPMDestinationPrinter || destination == kPMDestinationPreview) { + if (destination == kPMDestinationPrinter || + destination == kPMDestinationPreview) { mPrintViaSkPDF = true; } else if (destination == kPMDestinationFile) { AutoCFRelease destURL(nullptr); - status = - ::PMSessionCopyDestinationLocation(mPrintSession, mPMPrintSettings, destURL.receive()); + status = ::PMSessionCopyDestinationLocation( + mPrintSession, mPMPrintSettings, destURL.receive()); if (status == noErr) { AutoCFRelease destPathRef = CFURLCopyFileSystemPath(destURL, kCFURLPOSIXPathStyle); @@ -139,16 +144,20 @@ NS_IMETHODIMP nsDeviceContextSpecX::Init(nsIPrintSettings* aPS, bool aIsPrintPre // We don't actually currently support/use kOutputFormatPDF on mac, but // this is for completeness in case we add that (we probably need to in // order to support adding links into saved PDFs, for example). - Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, u"pdf_file"_ns, 1); + Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, + u"pdf_file"_ns, 1); } else { PMDestinationType destination; - OSStatus status = ::PMSessionGetDestinationType(mPrintSession, mPMPrintSettings, &destination); - if (status == noErr && - (destination == kPMDestinationFile || destination == kPMDestinationPreview || - destination == kPMDestinationProcessPDF)) { - Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, u"pdf_file"_ns, 1); + OSStatus status = ::PMSessionGetDestinationType( + mPrintSession, mPMPrintSettings, &destination); + if (status == noErr && (destination == kPMDestinationFile || + destination == kPMDestinationPreview || + destination == kPMDestinationProcessPDF)) { + Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, + u"pdf_file"_ns, 1); } else { - Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, u"unknown"_ns, 1); + Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, + u"unknown"_ns, 1); } } @@ -157,9 +166,9 @@ NS_IMETHODIMP nsDeviceContextSpecX::Init(nsIPrintSettings* aPS, bool aIsPrintPre NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -NS_IMETHODIMP nsDeviceContextSpecX::BeginDocument(const nsAString& aTitle, - const nsAString& aPrintToFileName, - int32_t aStartPage, int32_t aEndPage) { +NS_IMETHODIMP nsDeviceContextSpecX::BeginDocument( + const nsAString& aTitle, const nsAString& aPrintToFileName, + int32_t aStartPage, int32_t aEndPage) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; return NS_OK; @@ -168,7 +177,8 @@ NS_IMETHODIMP nsDeviceContextSpecX::BeginDocument(const nsAString& aTitle, } RefPtr nsDeviceContextSpecX::EndDocument() { - return nsIDeviceContextSpec::EndDocumentPromiseFromResult(DoEndDocument(), __func__); + return nsIDeviceContextSpec::EndDocumentPromiseFromResult(DoEndDocument(), + __func__); } nsresult nsDeviceContextSpecX::DoEndDocument() { @@ -183,14 +193,15 @@ nsresult nsDeviceContextSpecX::DoEndDocument() { return NS_ERROR_FAILURE; } AutoCFRelease pdfURL(nullptr); - // Note that the caller is responsible to release pdfURL according to nsILocalFileMac.idl, - // even though we didn't follow the Core Foundation naming conventions here (the method - // should've been called CopyCFURL). + // Note that the caller is responsible to release pdfURL according to + // nsILocalFileMac.idl, even though we didn't follow the Core Foundation + // naming conventions here (the method should've been called CopyCFURL). nsresult rv = tmpPDFFile->GetCFURL(pdfURL.receive()); NS_ENSURE_SUCCESS(rv, rv); PMDestinationType destination; - status = ::PMSessionGetDestinationType(mPrintSession, mPMPrintSettings, &destination); + status = ::PMSessionGetDestinationType(mPrintSession, mPMPrintSettings, + &destination); switch (destination) { case kPMDestinationPrinter: { @@ -200,13 +211,14 @@ nsresult nsDeviceContextSpecX::DoEndDocument() { return NS_ERROR_FAILURE; } CFStringRef mimeType = CFSTR("application/pdf"); - status = ::PMPrinterPrintWithFile(currentPrinter, mPMPrintSettings, mPageFormat, mimeType, - pdfURL); + status = ::PMPrinterPrintWithFile(currentPrinter, mPMPrintSettings, + mPageFormat, mimeType, pdfURL); break; } case kPMDestinationPreview: { // XXXjwatt Or should we use CocoaFileUtils::RevealFileInFinder(pdfURL); - AutoCFRelease pdfPath = CFURLCopyFileSystemPath(pdfURL, kCFURLPOSIXPathStyle); + AutoCFRelease pdfPath = + CFURLCopyFileSystemPath(pdfURL, kCFURLPOSIXPathStyle); NSString* path = (NSString*)CFStringRef(pdfPath); NSWorkspace* ws = [NSWorkspace sharedWorkspace]; [ws openFile:path]; @@ -214,8 +226,8 @@ nsresult nsDeviceContextSpecX::DoEndDocument() { } case kPMDestinationFile: { AutoCFRelease destURL(nullptr); - status = - ::PMSessionCopyDestinationLocation(mPrintSession, mPMPrintSettings, destURL.receive()); + status = ::PMSessionCopyDestinationLocation( + mPrintSession, mPMPrintSettings, destURL.receive()); if (status == noErr) { AutoCFRelease sourcePathRef = CFURLCopyFileSystemPath(pdfURL, kCFURLPOSIXPathStyle); @@ -234,12 +246,14 @@ nsresult nsDeviceContextSpecX::DoEndDocument() { if ([fileManager fileExistsAtPath:sourcePath]) { NSURL* src = static_cast(CFURLRef(pdfURL)); NSURL* dest = static_cast(CFURLRef(destURL)); - bool ok = [fileManager replaceItemAtURL:dest - withItemAtURL:src - backupItemName:nil - options:NSFileManagerItemReplacementUsingNewMetadataOnly - resultingItemURL:nil - error:nil]; + bool ok = [fileManager + replaceItemAtURL:dest + withItemAtURL:src + backupItemName:nil + options: + NSFileManagerItemReplacementUsingNewMetadataOnly + resultingItemURL:nil + error:nil]; if (!ok) { return NS_ERROR_FAILURE; } @@ -261,8 +275,8 @@ nsresult nsDeviceContextSpecX::DoEndDocument() { NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -void nsDeviceContextSpecX::GetPaperRect(double* aTop, double* aLeft, double* aBottom, - double* aRight) { +void nsDeviceContextSpecX::GetPaperRect(double* aTop, double* aLeft, + double* aBottom, double* aRight) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; PMRect paperRect; @@ -286,7 +300,8 @@ already_AddRefed nsDeviceContextSpecX::MakePrintTarget() { #ifdef MOZ_ENABLE_SKIA_PDF if (mPrintViaSkPDF) { // TODO: Add support for stream printing via SkPDF if we enable that again. - nsresult rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(mTempFile)); + nsresult rv = + NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(mTempFile)); NS_ENSURE_SUCCESS(rv, nullptr); nsAutoCString tempPath("tmp-printing.pdf"); mTempFile->AppendNative(tempPath); @@ -298,6 +313,6 @@ already_AddRefed nsDeviceContextSpecX::MakePrintTarget() { } #endif - return PrintTargetCG::CreateOrNull(mOutputStream, mPrintSession, mPageFormat, mPMPrintSettings, - size); + return PrintTargetCG::CreateOrNull(mOutputStream, mPrintSession, mPageFormat, + mPMPrintSettings, size); } diff --git a/widget/cocoa/nsDragService.mm b/widget/cocoa/nsDragService.mm index 4ac5c3cbc0d9..26bb834a89e6 100644 --- a/widget/cocoa/nsDragService.mm +++ b/widget/cocoa/nsDragService.mm @@ -49,24 +49,29 @@ nsDragService::nsDragService() nsDragService::~nsDragService() {} -NSImage* nsDragService::ConstructDragImage(nsINode* aDOMNode, const Maybe& aRegion, +NSImage* nsDragService::ConstructDragImage(nsINode* aDOMNode, + const Maybe& aRegion, NSPoint* aDragPoint) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; CGFloat scaleFactor = nsCocoaUtils::GetBackingScaleFactor(mNativeDragView); LayoutDeviceIntRect dragRect(0, 0, 20, 20); - NSImage* image = ConstructDragImage(mSourceNode, aRegion, mScreenPosition, &dragRect); + NSImage* image = + ConstructDragImage(mSourceNode, aRegion, mScreenPosition, &dragRect); if (!image) { // if no image was returned, just draw a rectangle NSSize size; - size.width = nsCocoaUtils::DevPixelsToCocoaPoints(dragRect.width, scaleFactor); - size.height = nsCocoaUtils::DevPixelsToCocoaPoints(dragRect.height, scaleFactor); + size.width = + nsCocoaUtils::DevPixelsToCocoaPoints(dragRect.width, scaleFactor); + size.height = + nsCocoaUtils::DevPixelsToCocoaPoints(dragRect.height, scaleFactor); image = [NSImage imageWithSize:size flipped:YES drawingHandler:^BOOL(NSRect dstRect) { [[NSColor grayColor] set]; - NSBezierPath* path = [NSBezierPath bezierPathWithRect:dstRect]; + NSBezierPath* path = + [NSBezierPath bezierPathWithRect:dstRect]; [path setLineWidth:2.0]; [path stroke]; return YES; @@ -85,8 +90,10 @@ NSImage* nsDragService::ConstructDragImage(nsINode* aDOMNode, const Maybe& aRegion, - CSSIntPoint aPoint, LayoutDeviceIntRect* aDragRect) { +NSImage* nsDragService::ConstructDragImage(nsINode* aDOMNode, + const Maybe& aRegion, + CSSIntPoint aPoint, + LayoutDeviceIntRect* aDragRect) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; CGFloat scaleFactor = nsCocoaUtils::GetBackingScaleFactor(mNativeDragView); @@ -97,8 +104,8 @@ NSImage* nsDragService::ConstructDragImage(nsINode* aDOMNode, const Maybewidth || !aDragRect->height)) { // just use some suitable defaults int32_t size = nsCocoaUtils::CocoaPointsToDevPixels(20, scaleFactor); - aDragRect->SetRect(pc->CSSPixelsToDevPixels(aPoint.x), pc->CSSPixelsToDevPixels(aPoint.y), size, - size); + aDragRect->SetRect(pc->CSSPixelsToDevPixels(aPoint.x), + pc->CSSPixelsToDevPixels(aPoint.y), size, size); } if (NS_FAILED(rv) || !surface) return nil; @@ -106,21 +113,23 @@ NSImage* nsDragService::ConstructDragImage(nsINode* aDOMNode, const Maybewidth; uint32_t height = aDragRect->height; - RefPtr dataSurface = - Factory::CreateDataSourceSurface(IntSize(width, height), SurfaceFormat::B8G8R8A8); + RefPtr dataSurface = Factory::CreateDataSourceSurface( + IntSize(width, height), SurfaceFormat::B8G8R8A8); DataSourceSurface::MappedSurface map; if (!dataSurface->Map(DataSourceSurface::MapType::READ_WRITE, &map)) { return nil; } RefPtr dt = Factory::CreateDrawTargetForData( - BackendType::CAIRO, map.mData, dataSurface->GetSize(), map.mStride, dataSurface->GetFormat()); + BackendType::CAIRO, map.mData, dataSurface->GetSize(), map.mStride, + dataSurface->GetFormat()); if (!dt) { dataSurface->Unmap(); return nil; } - dt->FillRect(gfx::Rect(0, 0, width, height), SurfacePattern(surface, ExtendMode::CLAMP), + dt->FillRect(gfx::Rect(0, 0, width, height), + SurfacePattern(surface, ExtendMode::CLAMP), DrawOptions(1.0f, CompositionOp::OP_SOURCE)); NSBitmapImageRep* imageRep = @@ -140,7 +149,8 @@ NSImage* nsDragService::ConstructDragImage(nsINode* aDOMNode, const MaybeUnmap(); - NSImage* image = - [[NSImage alloc] initWithSize:NSMakeSize(width / scaleFactor, height / scaleFactor)]; + NSImage* image = [[NSImage alloc] + initWithSize:NSMakeSize(width / scaleFactor, height / scaleFactor)]; [image addRepresentation:imageRep]; [imageRep release]; @@ -168,9 +178,9 @@ NSImage* nsDragService::ConstructDragImage(nsINode* aDOMNode, const Maybe& aRegion, - uint32_t aActionType) { +nsresult nsDragService::InvokeDragSessionImpl( + nsIArray* aTransferableArray, const Maybe& aRegion, + uint32_t aActionType) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; #ifdef NIGHTLY_BUILD @@ -178,10 +188,11 @@ nsresult nsDragService::InvokeDragSessionImpl(nsIArray* aTransferableArray, #endif if (!gLastDragView) { - // gLastDragView is non-null between -[ChildView mouseDown:] and -[ChildView mouseUp:]. - // If we get here with gLastDragView being null, that means that the mouse button has already - // been released. In that case we need to abort the drag because the OS won't know where to drop - // whatever's being dragged, and we might end up with a stuck drag & drop session. + // gLastDragView is non-null between -[ChildView mouseDown:] and -[ChildView + // mouseUp:]. If we get here with gLastDragView being null, that means that + // the mouse button has already been released. In that case we need to abort + // the drag because the OS won't know where to drop whatever's being + // dragged, and we might end up with a stuck drag & drop session. return NS_ERROR_FAILURE; } @@ -205,7 +216,8 @@ nsresult nsDragService::InvokeDragSessionImpl(nsIArray* aTransferableArray, gDraggedTransferables->GetLength(&count); for (uint32_t j = 0; j < count; j++) { - nsCOMPtr currentTransferable = do_QueryElementAt(aTransferableArray, j); + nsCOMPtr currentTransferable = + do_QueryElementAt(aTransferableArray, j); if (!currentTransferable) { return NS_ERROR_FAILURE; } @@ -234,7 +246,8 @@ nsresult nsDragService::InvokeDragSessionImpl(nsIArray* aTransferableArray, localDragRect.origin.x = draggingPoint.x; localDragRect.origin.y = draggingPoint.y - localDragRect.size.height; - NSDraggingItem* dragItem = [[NSDraggingItem alloc] initWithPasteboardWriter:pbItem]; + NSDraggingItem* dragItem = + [[NSDraggingItem alloc] initWithPasteboardWriter:pbItem]; [pbItem release]; [dragItem setDraggingFrame:localDragRect contents:image]; @@ -242,7 +255,8 @@ nsresult nsDragService::InvokeDragSessionImpl(nsIArray* aTransferableArray, nsBaseDragService::OpenDragPopup(); NSDraggingSession* draggingSession = [mNativeDragView - beginDraggingSessionWithItems:[NSArray arrayWithObject:[dragItem autorelease]] + beginDraggingSessionWithItems:[NSArray + arrayWithObject:[dragItem autorelease]] event:mNativeDragEvent source:mNativeDragView]; draggingSession.animatesToStartingPositionsOnCancelOrFail = @@ -261,24 +275,26 @@ nsDragService::GetData(nsITransferable* aTransferable, uint32_t aItemIndex) { return NS_ERROR_FAILURE; } - // get flavor list that includes all acceptable flavors (including ones obtained through - // conversion) + // get flavor list that includes all acceptable flavors (including ones + // obtained through conversion) nsTArray flavors; nsresult rv = aTransferable->FlavorsTransferableCanImport(flavors); if (NS_FAILED(rv)) { return NS_ERROR_FAILURE; } - // if this drag originated within Mozilla we should just use the cached data from - // when the drag started if possible + // if this drag originated within Mozilla we should just use the cached data + // from when the drag started if possible if (mDataItems) { - nsCOMPtr currentTransferable = do_QueryElementAt(mDataItems, aItemIndex); + nsCOMPtr currentTransferable = + do_QueryElementAt(mDataItems, aItemIndex); if (currentTransferable) { for (uint32_t i = 0; i < flavors.Length(); i++) { nsCString& flavorStr = flavors[i]; nsCOMPtr dataSupports; - rv = currentTransferable->GetTransferData(flavorStr.get(), getter_AddRefs(dataSupports)); + rv = currentTransferable->GetTransferData(flavorStr.get(), + getter_AddRefs(dataSupports)); if (NS_SUCCEEDED(rv)) { aTransferable->SetTransferData(flavorStr.get(), dataSupports); return NS_OK; // maybe try to fill in more types? Is there a point? @@ -304,7 +320,8 @@ nsDragService::GetData(nsITransferable* aTransferable, uint32_t aItemIndex) { // now check the actual clipboard for data for (uint32_t i = 0; i < flavors.Length(); i++) { - nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem(aTransferable, flavors[i], item); + nsCocoaUtils::SetTransferDataForTypeFromPasteboardItem(aTransferable, + flavors[i], item); } return NS_OK; @@ -327,7 +344,8 @@ nsDragService::IsDataFlavorSupported(const char* aDataFlavor, bool* _retval) { uint32_t dataItemsCount; mDataItems->GetLength(&dataItemsCount); for (unsigned int i = 0; i < dataItemsCount; i++) { - nsCOMPtr currentTransferable = do_QueryElementAt(mDataItems, i); + nsCOMPtr currentTransferable = + do_QueryElementAt(mDataItems, i); if (!currentTransferable) continue; nsTArray flavors; @@ -352,7 +370,8 @@ nsDragService::IsDataFlavorSupported(const char* aDataFlavor, bool* _retval) { type = [UTIHelper stringFromPboardType:NSPasteboardTypeString]; } else if (dataFlavor.EqualsLiteral(kHTMLMime)) { type = [UTIHelper stringFromPboardType:NSPasteboardTypeHTML]; - } else if (dataFlavor.EqualsLiteral(kURLMime) || dataFlavor.EqualsLiteral(kURLDataMime)) { + } else if (dataFlavor.EqualsLiteral(kURLMime) || + dataFlavor.EqualsLiteral(kURLDataMime)) { type = [UTIHelper stringFromPboardType:kPublicUrlPboardType]; } else if (dataFlavor.EqualsLiteral(kURLDescriptionMime)) { type = [UTIHelper stringFromPboardType:kPublicUrlNamePboardType]; @@ -362,9 +381,10 @@ nsDragService::IsDataFlavorSupported(const char* aDataFlavor, bool* _retval) { type = [UTIHelper stringFromPboardType:kMozCustomTypesPboardType]; } - NSString* availableType = - [globalDragPboard availableTypeFromArray:[NSArray arrayWithObjects:(id)type, nil]]; - if (availableType && nsCocoaUtils::IsValidPasteboardType(availableType, allowFileURL)) { + NSString* availableType = [globalDragPboard + availableTypeFromArray:[NSArray arrayWithObjects:(id)type, nil]]; + if (availableType && + nsCocoaUtils::IsValidPasteboardType(availableType, allowFileURL)) { *_retval = true; } @@ -396,19 +416,22 @@ nsDragService::GetNumDropItems(uint32_t* aNumItems) { } NS_IMETHODIMP -nsDragService::UpdateDragImage(nsINode* aImage, int32_t aImageX, int32_t aImageY) { +nsDragService::UpdateDragImage(nsINode* aImage, int32_t aImageX, + int32_t aImageY) { nsBaseDragService::UpdateDragImage(aImage, aImageX, aImageY); mDragImageChanged = true; return NS_OK; } -void nsDragService::DragMovedWithView(NSDraggingSession* aSession, NSPoint aPoint) { +void nsDragService::DragMovedWithView(NSDraggingSession* aSession, + NSPoint aPoint) { aPoint.y = nsCocoaUtils::FlippedScreenY(aPoint.y); // XXX It feels like we should be using the backing scale factor at aPoint // rather than the initial drag view, but I've seen no ill effects of this. CGFloat scaleFactor = nsCocoaUtils::GetBackingScaleFactor(mNativeDragView); - LayoutDeviceIntPoint devPoint = nsCocoaUtils::CocoaPointsToDevPixels(aPoint, scaleFactor); + LayoutDeviceIntPoint devPoint = + nsCocoaUtils::CocoaPointsToDevPixels(aPoint, scaleFactor); // If the image has changed, call enumerateDraggingItemsWithOptions to get // the item being dragged and update its image. @@ -422,32 +445,39 @@ void nsDragService::DragMovedWithView(NSDraggingSession* aSession, NSPoint aPoin } if (pc) { - void (^changeImageBlock)(NSDraggingItem*, NSInteger, BOOL*) = - ^(NSDraggingItem* draggingItem, NSInteger idx, BOOL* stop) { - // We never add more than one item right now, but check just in case. - if (idx > 0) { - return; - } + void (^changeImageBlock)(NSDraggingItem*, NSInteger, BOOL*) = ^( + NSDraggingItem* draggingItem, NSInteger idx, BOOL* stop) { + // We never add more than one item right now, but check just in case. + if (idx > 0) { + return; + } - nsPoint pt = - LayoutDevicePixel::ToAppUnits(devPoint, pc->DeviceContext()->AppUnitsPerDevPixel()); - CSSIntPoint screenPoint = CSSIntPoint(nsPresContext::AppUnitsToIntCSSPixels(pt.x), - nsPresContext::AppUnitsToIntCSSPixels(pt.y)); + nsPoint pt = LayoutDevicePixel::ToAppUnits( + devPoint, pc->DeviceContext()->AppUnitsPerDevPixel()); + CSSIntPoint screenPoint = + CSSIntPoint(nsPresContext::AppUnitsToIntCSSPixels(pt.x), + nsPresContext::AppUnitsToIntCSSPixels(pt.y)); - // Create a new image; if one isn't returned don't change the current one. - LayoutDeviceIntRect newRect; - NSImage* image = ConstructDragImage(mSourceNode, Nothing(), screenPoint, &newRect); - if (image) { - NSRect draggingRect = nsCocoaUtils::GeckoRectToCocoaRectDevPix(newRect, scaleFactor); - [draggingItem setDraggingFrame:draggingRect contents:image]; - } - }; + // Create a new image; if one isn't returned don't change the current + // one. + LayoutDeviceIntRect newRect; + NSImage* image = + ConstructDragImage(mSourceNode, Nothing(), screenPoint, &newRect); + if (image) { + NSRect draggingRect = + nsCocoaUtils::GeckoRectToCocoaRectDevPix(newRect, scaleFactor); + [draggingItem setDraggingFrame:draggingRect contents:image]; + } + }; - [aSession enumerateDraggingItemsWithOptions:NSDraggingItemEnumerationConcurrent - forView:nil - classes:[NSArray arrayWithObject:[NSPasteboardItem class]] - searchOptions:@{} - usingBlock:changeImageBlock]; + [aSession + enumerateDraggingItemsWithOptions:NSDraggingItemEnumerationConcurrent + forView:nil + classes:[NSArray + arrayWithObject: + [NSPasteboardItem class]] + searchOptions:@{} + usingBlock:changeImageBlock]; } } diff --git a/widget/cocoa/nsFilePicker.mm b/widget/cocoa/nsFilePicker.mm index ec0100e569db..8c542c20736c 100644 --- a/widget/cocoa/nsFilePicker.mm +++ b/widget/cocoa/nsFilePicker.mm @@ -59,9 +59,11 @@ static void SetShowHiddenFileState(NSSavePanel* panel) { if (gCallSecretHiddenFileAPI) { // invoke a method to get a Cocoa-internal nav view SEL navViewSelector = @selector(_navView); - NSMethodSignature* navViewSignature = [panel methodSignatureForSelector:navViewSelector]; + NSMethodSignature* navViewSignature = + [panel methodSignatureForSelector:navViewSelector]; if (!navViewSignature) return; - NSInvocation* navViewInvocation = [NSInvocation invocationWithMethodSignature:navViewSignature]; + NSInvocation* navViewInvocation = + [NSInvocation invocationWithMethodSignature:navViewSignature]; [navViewInvocation setSelector:navViewSelector]; [navViewInvocation setTarget:panel]; [navViewInvocation invoke]; @@ -90,27 +92,32 @@ nsFilePicker::nsFilePicker() : mSelectedTypeIndex(0) {} nsFilePicker::~nsFilePicker() {} -void nsFilePicker::InitNative(nsIWidget* aParent, const nsAString& aTitle) { mTitle = aTitle; } +void nsFilePicker::InitNative(nsIWidget* aParent, const nsAString& aTitle) { + mTitle = aTitle; +} NSView* nsFilePicker::GetAccessoryView() { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - NSView* accessoryView = [[[NSView alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)] autorelease]; + NSView* accessoryView = + [[[NSView alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)] autorelease]; // Set a label's default value. NSString* label = @"Format:"; // Try to get the localized string. - nsCOMPtr sbs = do_GetService(NS_STRINGBUNDLE_CONTRACTID); + nsCOMPtr sbs = + do_GetService(NS_STRINGBUNDLE_CONTRACTID); nsCOMPtr bundle; - nsresult rv = - sbs->CreateBundle("chrome://global/locale/filepicker.properties", getter_AddRefs(bundle)); + nsresult rv = sbs->CreateBundle( + "chrome://global/locale/filepicker.properties", getter_AddRefs(bundle)); if (NS_SUCCEEDED(rv)) { nsAutoString locaLabel; rv = bundle->GetStringFromName("formatLabel", locaLabel); if (NS_SUCCEEDED(rv)) { - label = [NSString stringWithCharacters:reinterpret_cast(locaLabel.get()) - length:locaLabel.Length()]; + label = [NSString + stringWithCharacters:reinterpret_cast(locaLabel.get()) + length:locaLabel.Length()]; } } @@ -127,8 +134,9 @@ NSView* nsFilePicker::GetAccessoryView() { [textField sizeToFit]; // set up popup button - NSPopUpButton* popupButton = [[[NSPopUpButton alloc] initWithFrame:NSMakeRect(0, 0, 0, 0) - pullsDown:NO] autorelease]; + NSPopUpButton* popupButton = + [[[NSPopUpButton alloc] initWithFrame:NSMakeRect(0, 0, 0, 0) + pullsDown:NO] autorelease]; uint32_t numMenuItems = mTitles.Length(); for (uint32_t i = 0; i < numMenuItems; i++) { const nsString& currentTitle = mTitles[i]; @@ -136,11 +144,13 @@ NSView* nsFilePicker::GetAccessoryView() { if (currentTitle.IsEmpty()) { const nsString& currentFilter = mFilters[i]; titleString = - [[NSString alloc] initWithCharacters:reinterpret_cast(currentFilter.get()) + [[NSString alloc] initWithCharacters:reinterpret_cast( + currentFilter.get()) length:currentFilter.Length()]; } else { titleString = - [[NSString alloc] initWithCharacters:reinterpret_cast(currentTitle.get()) + [[NSString alloc] initWithCharacters:reinterpret_cast( + currentTitle.get()) length:currentTitle.Length()]; } [popupButton addItemWithTitle:titleString]; @@ -149,28 +159,34 @@ NSView* nsFilePicker::GetAccessoryView() { if (mSelectedTypeIndex >= 0 && (uint32_t)mSelectedTypeIndex < numMenuItems) [popupButton selectItemAtIndex:mSelectedTypeIndex]; [popupButton setTag:kSaveTypeControlTag]; - [popupButton sizeToFit]; // we have to do sizeToFit to get the height calculated for us - // This is just a default width that works well, doesn't truncate the vast majority of - // things that might end up in the menu. + [popupButton sizeToFit]; // we have to do sizeToFit to get the height + // calculated for us + // This is just a default width that works well, doesn't truncate the vast + // majority of things that might end up in the menu. [popupButton setFrameSize:NSMakeSize(180, [popupButton frame].size.height)]; - // position everything based on control sizes with kAccessoryViewPadding pix padding - // on each side kAccessoryViewPadding pix horizontal padding between controls + // position everything based on control sizes with kAccessoryViewPadding pix + // padding on each side kAccessoryViewPadding pix horizontal padding between + // controls float greatestHeight = [textField frame].size.height; if ([popupButton frame].size.height > greatestHeight) greatestHeight = [popupButton frame].size.height; float totalViewHeight = greatestHeight + kAccessoryViewPadding * 2; - float totalViewWidth = - [textField frame].size.width + [popupButton frame].size.width + kAccessoryViewPadding * 3; + float totalViewWidth = [textField frame].size.width + + [popupButton frame].size.width + + kAccessoryViewPadding * 3; [accessoryView setFrameSize:NSMakeSize(totalViewWidth, totalViewHeight)]; float textFieldOriginY = - ((greatestHeight - [textField frame].size.height) / 2 + 1) + kAccessoryViewPadding; - [textField setFrameOrigin:NSMakePoint(kAccessoryViewPadding, textFieldOriginY)]; + ((greatestHeight - [textField frame].size.height) / 2 + 1) + + kAccessoryViewPadding; + [textField + setFrameOrigin:NSMakePoint(kAccessoryViewPadding, textFieldOriginY)]; float popupOriginX = [textField frame].size.width + kAccessoryViewPadding * 2; float popupOriginY = - ((greatestHeight - [popupButton frame].size.height) / 2) + kAccessoryViewPadding; + ((greatestHeight - [popupButton frame].size.height) / 2) + + kAccessoryViewPadding; [popupButton setFrameOrigin:NSMakePoint(popupOriginX, popupOriginY)]; [accessoryView addSubview:textField]; @@ -255,9 +271,10 @@ static void UpdatePanelFileTypes(NSOpenPanel* aPanel, NSArray* aFilters) { } @end -// Use OpenPanel to do a GetFile. Returns |returnOK| if the user presses OK in the dialog. -nsIFilePicker::ResultCode nsFilePicker::GetLocalFiles(bool inAllowMultiple, - nsCOMArray& outFiles) { +// Use OpenPanel to do a GetFile. Returns |returnOK| if the user presses OK in +// the dialog. +nsIFilePicker::ResultCode nsFilePicker::GetLocalFiles( + bool inAllowMultiple, nsCOMArray& outFiles) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; ResultCode retVal = nsIFilePicker::returnCancel; @@ -308,10 +325,11 @@ nsIFilePicker::ResultCode nsFilePicker::GetLocalFiles(bool inAllowMultiple, [observer setOpenPanel:thePanel]; [observer setFilePicker:this]; - [[NSNotificationCenter defaultCenter] addObserver:observer - selector:@selector(menuChangedItem:) - name:NSMenuWillSendActionNotification - object:nil]; + [[NSNotificationCenter defaultCenter] + addObserver:observer + selector:@selector(menuChangedItem:) + name:NSMenuWillSendActionNotification + object:nil]; UpdatePanelFileTypes(thePanel, filters); result = [thePanel runModal]; @@ -343,7 +361,8 @@ nsIFilePicker::ResultCode nsFilePicker::GetLocalFiles(bool inAllowMultiple, nsCOMPtr localFile; NS_NewLocalFile(u""_ns, true, getter_AddRefs(localFile)); nsCOMPtr macLocalFile = do_QueryInterface(localFile); - if (macLocalFile && NS_SUCCEEDED(macLocalFile->InitWithCFURL((CFURLRef)url))) { + if (macLocalFile && + NS_SUCCEEDED(macLocalFile->InitWithCFURL((CFURLRef)url))) { outFiles.AppendObject(localFile); } } @@ -355,10 +374,13 @@ nsIFilePicker::ResultCode nsFilePicker::GetLocalFiles(bool inAllowMultiple, NS_OBJC_END_TRY_BLOCK_RETURN(nsIFilePicker::returnOK); } -// Use OpenPanel to do a GetFolder. Returns |returnOK| if the user presses OK in the dialog. +// Use OpenPanel to do a GetFolder. Returns |returnOK| if the user presses OK in +// the dialog. nsIFilePicker::ResultCode nsFilePicker::GetLocalFolder(nsIFile** outFile) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - NS_ASSERTION(outFile, "this protected member function expects a null initialized out pointer"); + NS_ASSERTION( + outFile, + "this protected member function expects a null initialized out pointer"); ResultCode retVal = nsIFilePicker::returnCancel; NSOpenPanel* thePanel = [NSOpenPanel openPanel]; @@ -394,7 +416,8 @@ nsIFilePicker::ResultCode nsFilePicker::GetLocalFolder(nsIFile** outFile) { nsCOMPtr localFile; NS_NewLocalFile(u""_ns, true, getter_AddRefs(localFile)); nsCOMPtr macLocalFile = do_QueryInterface(localFile); - if (macLocalFile && NS_SUCCEEDED(macLocalFile->InitWithCFURL((CFURLRef)theURL))) { + if (macLocalFile && + NS_SUCCEEDED(macLocalFile->InitWithCFURL((CFURLRef)theURL))) { *outFile = localFile; NS_ADDREF(*outFile); retVal = returnOK; @@ -409,7 +432,9 @@ nsIFilePicker::ResultCode nsFilePicker::GetLocalFolder(nsIFile** outFile) { // Returns |returnOK| if the user presses OK in the dialog. nsIFilePicker::ResultCode nsFilePicker::PutLocalFile(nsIFile** outFile) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - NS_ASSERTION(outFile, "this protected member function expects a null initialized out pointer"); + NS_ASSERTION( + outFile, + "this protected member function expects a null initialized out pointer"); ResultCode retVal = nsIFilePicker::returnCancel; NSSavePanel* thePanel = [NSSavePanel savePanel]; @@ -423,8 +448,9 @@ nsIFilePicker::ResultCode nsFilePicker::PutLocalFile(nsIFile** outFile) { [thePanel setAccessoryView:accessoryView]; // set up default file name - NSString* defaultFilename = [NSString stringWithCharacters:(const unichar*)mDefaultFilename.get() - length:mDefaultFilename.Length()]; + NSString* defaultFilename = + [NSString stringWithCharacters:(const unichar*)mDefaultFilename.get() + length:mDefaultFilename.Length()]; // Set up the allowed type. This prevents the extension from being selected. NSString* extension = defaultFilename.pathExtension; @@ -440,12 +466,13 @@ nsIFilePicker::ResultCode nsFilePicker::PutLocalFile(nsIFile** outFile) { // trying to add a non-default extension. To avoid the confusion, we ensure // that all extensions are shown in the panel if the remaining extension is // known by the OS. - NSString* fileName = [[defaultFilename lastPathComponent] stringByDeletingPathExtension]; + NSString* fileName = + [[defaultFilename lastPathComponent] stringByDeletingPathExtension]; NSString* otherExtension = fileName.pathExtension; if (otherExtension.length != 0) { // There's another extension here. Get the UTI. - CFStringRef type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, - (CFStringRef)otherExtension, NULL); + CFStringRef type = UTTypeCreatePreferredIdentifierForTag( + kUTTagClassFilenameExtension, (CFStringRef)otherExtension, NULL); if (type) { if (!CFStringHasPrefix(type, CFSTR("dyn."))) { // We have a UTI, otherwise the type would have a "dyn." prefix. Ensure @@ -480,11 +507,13 @@ nsIFilePicker::ResultCode nsFilePicker::PutLocalFile(nsIFile** outFile) { nsCOMPtr localFile; NS_NewLocalFile(u""_ns, true, getter_AddRefs(localFile)); nsCOMPtr macLocalFile = do_QueryInterface(localFile); - if (macLocalFile && NS_SUCCEEDED(macLocalFile->InitWithCFURL((CFURLRef)fileURL))) { + if (macLocalFile && + NS_SUCCEEDED(macLocalFile->InitWithCFURL((CFURLRef)fileURL))) { *outFile = localFile; NS_ADDREF(*outFile); - // We tell if we are replacing or not by just looking to see if the file exists. - // The user could not have hit OK and not meant to replace the file. + // We tell if we are replacing or not by just looking to see if the file + // exists. The user could not have hit OK and not meant to replace the + // file. if ([[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) retVal = returnReplace; else @@ -505,7 +534,8 @@ NSArray* nsFilePicker::GetFilterList() { } if (mFilters.Length() <= (uint32_t)mSelectedTypeIndex) { - NS_WARNING("An out of range index has been selected. Using the first index instead."); + NS_WARNING("An out of range index has been selected. Using the first index " + "instead."); mSelectedTypeIndex = 0; } @@ -522,17 +552,21 @@ NSArray* nsFilePicker::GetFilterList() { // in the format "ext" by NSOpenPanel. So we need to filter some characters. NSMutableString* filterString = [[[NSMutableString alloc] initWithString:[NSString - stringWithCharacters:reinterpret_cast(filterWide.get()) - length:filterWide.Length()]] autorelease]; - NSCharacterSet* set = [NSCharacterSet characterSetWithCharactersInString:@". *"]; + stringWithCharacters:reinterpret_cast( + filterWide.get()) + length:filterWide.Length()]] + autorelease]; + NSCharacterSet* set = + [NSCharacterSet characterSetWithCharactersInString:@". *"]; NSRange range = [filterString rangeOfCharacterFromSet:set]; while (range.length) { [filterString replaceCharactersInRange:range withString:@""]; range = [filterString rangeOfCharacterFromSet:set]; } - return - [[[NSArray alloc] initWithArray:[filterString componentsSeparatedByString:@";"]] autorelease]; + return [[[NSArray alloc] + initWithArray:[filterString componentsSeparatedByString:@";"]] + autorelease]; NS_OBJC_END_TRY_BLOCK_RETURN(nil); } @@ -546,8 +580,10 @@ void nsFilePicker::SetDialogTitle(const nsString& inTitle, id aPanel) { length:inTitle.Length()]]; if (!mOkButtonLabel.IsEmpty()) { - [aPanel setPrompt:[NSString stringWithCharacters:(const unichar*)mOkButtonLabel.get() - length:mOkButtonLabel.Length()]]; + [aPanel + setPrompt:[NSString + stringWithCharacters:(const unichar*)mOkButtonLabel.get() + length:mOkButtonLabel.Length()]]; } NS_OBJC_END_TRY_IGNORE_BLOCK; @@ -562,9 +598,9 @@ NSString* nsFilePicker::PanelDefaultDirectory() { if (mDisplayDirectory) { nsAutoString pathStr; mDisplayDirectory->GetPath(pathStr); - directory = - [[[NSString alloc] initWithCharacters:reinterpret_cast(pathStr.get()) - length:pathStr.Length()] autorelease]; + directory = [[[NSString alloc] + initWithCharacters:reinterpret_cast(pathStr.get()) + length:pathStr.Length()] autorelease]; } return directory; @@ -602,7 +638,9 @@ NS_IMETHODIMP nsFilePicker::SetDefaultString(const nsAString& aString) { return NS_OK; } -NS_IMETHODIMP nsFilePicker::GetDefaultString(nsAString& aString) { return NS_ERROR_FAILURE; } +NS_IMETHODIMP nsFilePicker::GetDefaultString(nsAString& aString) { + return NS_ERROR_FAILURE; +} // The default extension to use for files NS_IMETHODIMP nsFilePicker::GetDefaultExtension(nsAString& aExtension) { @@ -610,7 +648,9 @@ NS_IMETHODIMP nsFilePicker::GetDefaultExtension(nsAString& aExtension) { return NS_OK; } -NS_IMETHODIMP nsFilePicker::SetDefaultExtension(const nsAString& aExtension) { return NS_OK; } +NS_IMETHODIMP nsFilePicker::SetDefaultExtension(const nsAString& aExtension) { + return NS_OK; +} // Append an entry to the filters array NS_IMETHODIMP diff --git a/widget/cocoa/nsLookAndFeel.mm b/widget/cocoa/nsLookAndFeel.mm index 855bdd89641c..7c84c8a2371f 100644 --- a/widget/cocoa/nsLookAndFeel.mm +++ b/widget/cocoa/nsLookAndFeel.mm @@ -47,18 +47,22 @@ void nsLookAndFeel::NativeInit() { } static nscolor GetColorFromNSColor(NSColor* aColor) { - NSColor* deviceColor = [aColor colorUsingColorSpaceName:NSDeviceRGBColorSpace]; + NSColor* deviceColor = + [aColor colorUsingColorSpaceName:NSDeviceRGBColorSpace]; return NS_RGBA((unsigned int)(deviceColor.redComponent * 255.0), (unsigned int)(deviceColor.greenComponent * 255.0), (unsigned int)(deviceColor.blueComponent * 255.0), (unsigned int)(deviceColor.alphaComponent * 255.0)); } -static nscolor GetColorFromNSColorWithCustomAlpha(NSColor* aColor, float alpha) { - NSColor* deviceColor = [aColor colorUsingColorSpaceName:NSDeviceRGBColorSpace]; +static nscolor GetColorFromNSColorWithCustomAlpha(NSColor* aColor, + float alpha) { + NSColor* deviceColor = + [aColor colorUsingColorSpaceName:NSDeviceRGBColorSpace]; return NS_RGBA((unsigned int)(deviceColor.redComponent * 255.0), (unsigned int)(deviceColor.greenComponent * 255.0), - (unsigned int)(deviceColor.blueComponent * 255.0), (unsigned int)(alpha * 255.0)); + (unsigned int)(deviceColor.blueComponent * 255.0), + (unsigned int)(alpha * 255.0)); } // Turns an opaque selection color into a partially transparent selection color, @@ -74,11 +78,12 @@ static nscolor GetColorFromNSColorWithCustomAlpha(NSColor* aColor, float alpha) // whereas white text on dark blue (which what you get if you mix // partially-transparent light blue with the black textbox background) has much // better contrast. -nscolor nsLookAndFeel::ProcessSelectionBackground(nscolor aColor, ColorScheme aScheme) { +nscolor nsLookAndFeel::ProcessSelectionBackground(nscolor aColor, + ColorScheme aScheme) { if (aScheme == ColorScheme::Dark) { // When we use a dark selection color, we do not change alpha because we do - // not use dark selection in content. The dark system color is appropriate for - // Firefox UI without needing to adjust its alpha. + // not use dark selection in content. The dark system color is appropriate + // for Firefox UI without needing to adjust its alpha. return aColor; } uint16_t hue, sat, value; @@ -100,7 +105,8 @@ nscolor nsLookAndFeel::ProcessSelectionBackground(nscolor aColor, ColorScheme aS return resultColor; } -nsresult nsLookAndFeel::NativeGetColor(ColorID aID, ColorScheme aScheme, nscolor& aColor) { +nsresult nsLookAndFeel::NativeGetColor(ColorID aID, ColorScheme aScheme, + nscolor& aColor) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK NSAppearance.currentAppearance = NSAppearanceForColorScheme(aScheme); @@ -108,18 +114,19 @@ nsresult nsLookAndFeel::NativeGetColor(ColorID aID, ColorScheme aScheme, nscolor nscolor color = 0; switch (aID) { case ColorID::Infobackground: - color = aScheme == ColorScheme::Light ? NS_RGB(0xdd, 0xdd, 0xdd) - : GetColorFromNSColor(NSColor.windowBackgroundColor); + color = aScheme == ColorScheme::Light + ? NS_RGB(0xdd, 0xdd, 0xdd) + : GetColorFromNSColor(NSColor.windowBackgroundColor); break; case ColorID::Highlight: - color = ProcessSelectionBackground(GetColorFromNSColor(NSColor.selectedTextBackgroundColor), - aScheme); + color = ProcessSelectionBackground( + GetColorFromNSColor(NSColor.selectedTextBackgroundColor), aScheme); break; // This is used to gray out the selection when it's not focused. Used with // nsISelectionController::SELECTION_DISABLED. case ColorID::TextSelectDisabledBackground: - color = ProcessSelectionBackground(GetColorFromNSColor(NSColor.secondarySelectedControlColor), - aScheme); + color = ProcessSelectionBackground( + GetColorFromNSColor(NSColor.secondarySelectedControlColor), aScheme); break; case ColorID::MozMenuhoverdisabled: aColor = NS_TRANSPARENT; @@ -158,23 +165,26 @@ nsresult nsLookAndFeel::NativeGetColor(ColorID aID, ColorScheme aScheme, nscolor // // css2 system colors http://www.w3.org/TR/REC-CSS2/ui.html#system-colors // - // It's really hard to effectively map these to the Appearance Manager properly, - // since they are modeled word for word after the win32 system colors and don't have any - // real counterparts in the Mac world. I'm sure we'll be tweaking these for - // years to come. + // It's really hard to effectively map these to the Appearance Manager + // properly, since they are modeled word for word after the win32 system + // colors and don't have any real counterparts in the Mac world. I'm sure + // we'll be tweaking these for years to come. // - // Thanks to mpt26@student.canterbury.ac.nz for the hardcoded values that form the defaults + // Thanks to mpt26@student.canterbury.ac.nz for the hardcoded values that + // form the defaults // if querying the Appearance Manager fails ;) // case ColorID::MozMacDefaultbuttontext: color = NS_RGB(0xFF, 0xFF, 0xFF); break; case ColorID::MozButtonactivetext: - // Pre-macOS 12, pressed buttons were filled with the highlight color and the text was white. - // Starting with macOS 12, pressed (non-default) buttons are filled with medium gray and the - // text color is the same as in the non-pressed state. - color = nsCocoaFeatures::OnMontereyOrLater() ? GetColorFromNSColor(NSColor.controlTextColor) - : NS_RGB(0xFF, 0xFF, 0xFF); + // Pre-macOS 12, pressed buttons were filled with the highlight color and + // the text was white. Starting with macOS 12, pressed (non-default) + // buttons are filled with medium gray and the text color is the same as + // in the non-pressed state. + color = nsCocoaFeatures::OnMontereyOrLater() + ? GetColorFromNSColor(NSColor.controlTextColor) + : NS_RGB(0xFF, 0xFF, 0xFF); break; case ColorID::Menutext: case ColorID::Infotext: @@ -209,18 +219,22 @@ nsresult nsLookAndFeel::NativeGetColor(ColorID aID, ColorScheme aScheme, nscolor break; case ColorID::Buttonshadow: case ColorID::Threeddarkshadow: - color = aScheme == ColorScheme::Dark ? *GenericDarkColor(aID) : NS_RGB(0xDC, 0xDC, 0xDC); + color = aScheme == ColorScheme::Dark ? *GenericDarkColor(aID) + : NS_RGB(0xDC, 0xDC, 0xDC); break; case ColorID::Threedshadow: - color = aScheme == ColorScheme::Dark ? *GenericDarkColor(aID) : NS_RGB(0xE0, 0xE0, 0xE0); + color = aScheme == ColorScheme::Dark ? *GenericDarkColor(aID) + : NS_RGB(0xE0, 0xE0, 0xE0); break; case ColorID::Threedface: - color = aScheme == ColorScheme::Dark ? *GenericDarkColor(aID) : NS_RGB(0xF0, 0xF0, 0xF0); + color = aScheme == ColorScheme::Dark ? *GenericDarkColor(aID) + : NS_RGB(0xF0, 0xF0, 0xF0); break; case ColorID::Threedlightshadow: case ColorID::Buttonborder: case ColorID::MozDisabledfield: - color = aScheme == ColorScheme::Dark ? *GenericDarkColor(aID) : NS_RGB(0xDA, 0xDA, 0xDA); + color = aScheme == ColorScheme::Dark ? *GenericDarkColor(aID) + : NS_RGB(0xDA, 0xDA, 0xDA); break; case ColorID::Menu: color = GetColorFromNSColor(NSColor.textBackgroundColor); @@ -248,7 +262,8 @@ nsresult nsLookAndFeel::NativeGetColor(ColorID aID, ColorScheme aScheme, nscolor color = GetColorFromNSColor(NSColor.controlTextColor); break; case ColorID::MozMacFocusring: - color = GetColorFromNSColorWithCustomAlpha(NSColor.keyboardFocusIndicatorColor, 0.48); + color = GetColorFromNSColorWithCustomAlpha( + NSColor.keyboardFocusIndicatorColor, 0.48); break; case ColorID::MozMacMenutextdisable: color = NS_RGB(0x98, 0x98, 0x98); @@ -266,11 +281,13 @@ nsresult nsLookAndFeel::NativeGetColor(ColorID aID, ColorScheme aScheme, nscolor break; case ColorID::MozEventreerow: // Background color of even list rows. - color = GetColorFromNSColor(NSColor.controlAlternatingRowBackgroundColors[0]); + color = + GetColorFromNSColor(NSColor.controlAlternatingRowBackgroundColors[0]); break; case ColorID::MozOddtreerow: // Background color of odd list rows. - color = GetColorFromNSColor(NSColor.controlAlternatingRowBackgroundColors[1]); + color = + GetColorFromNSColor(NSColor.controlAlternatingRowBackgroundColors[1]); break; case ColorID::MozNativehyperlinktext: color = GetColorFromNSColor(NSColor.linkColor); @@ -281,13 +298,16 @@ nsresult nsLookAndFeel::NativeGetColor(ColorID aID, ColorScheme aScheme, nscolor case ColorID::MozMacTooltip: case ColorID::MozMacMenupopup: case ColorID::MozMacMenuitem: - color = aScheme == ColorScheme::Light ? NS_RGB(0xf6, 0xf6, 0xf6) : NS_RGB(0x28, 0x28, 0x28); + color = aScheme == ColorScheme::Light ? NS_RGB(0xf6, 0xf6, 0xf6) + : NS_RGB(0x28, 0x28, 0x28); break; case ColorID::MozMacSourceList: - color = aScheme == ColorScheme::Light ? NS_RGB(0xf6, 0xf6, 0xf6) : NS_RGB(0x2d, 0x2d, 0x2d); + color = aScheme == ColorScheme::Light ? NS_RGB(0xf6, 0xf6, 0xf6) + : NS_RGB(0x2d, 0x2d, 0x2d); break; case ColorID::MozMacSourceListSelection: - color = aScheme == ColorScheme::Light ? NS_RGB(0xd3, 0xd3, 0xd3) : NS_RGB(0x2d, 0x2d, 0x2d); + color = aScheme == ColorScheme::Light ? NS_RGB(0xd3, 0xd3, 0xd3) + : NS_RGB(0x2d, 0x2d, 0x2d); break; case ColorID::MozMacActiveMenuitem: case ColorID::MozMacActiveSourceListSelection: @@ -298,7 +318,8 @@ nsresult nsLookAndFeel::NativeGetColor(ColorID aID, ColorScheme aScheme, nscolor case ColorID::Inactivecaption: case ColorID::Activecaption: { if (aScheme == ColorScheme::Light && - NSWorkspace.sharedWorkspace.accessibilityDisplayShouldIncreaseContrast) { + NSWorkspace.sharedWorkspace + .accessibilityDisplayShouldIncreaseContrast) { // This has better contrast than the stand-in colors. aColor = GetColorFromNSColor(NSColor.windowBackgroundColor); return NS_OK; @@ -410,11 +431,13 @@ nsresult nsLookAndFeel::NativeGetInt(IntID aID, int32_t& aResult) { aResult = NS_ALERT_TOP; break; case IntID::TabFocusModel: - aResult = [NSApp isFullKeyboardAccessEnabled] ? nsIContent::eTabFocus_any - : nsIContent::eTabFocus_textControlsMask; + aResult = [NSApp isFullKeyboardAccessEnabled] + ? nsIContent::eTabFocus_any + : nsIContent::eTabFocus_textControlsMask; break; case IntID::ScrollToClick: { - aResult = [[NSUserDefaults standardUserDefaults] boolForKey:@"AppleScrollerPagingBehavior"]; + aResult = [[NSUserDefaults standardUserDefaults] + boolForKey:@"AppleScrollerPagingBehavior"]; } break; case IntID::ChosenMenuItemsShouldBlink: aResult = 1; @@ -444,19 +467,24 @@ nsresult nsLookAndFeel::NativeGetInt(IntID aID, int32_t& aResult) { aResult = SystemWantsDarkTheme(); break; case IntID::PrefersReducedMotion: - aResult = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion; + aResult = + NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion; break; case IntID::PrefersReducedTransparency: - aResult = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceTransparency; + aResult = NSWorkspace.sharedWorkspace + .accessibilityDisplayShouldReduceTransparency; break; case IntID::InvertedColors: - aResult = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldInvertColors; + aResult = + NSWorkspace.sharedWorkspace.accessibilityDisplayShouldInvertColors; break; case IntID::UseAccessibilityTheme: - aResult = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldIncreaseContrast; + aResult = NSWorkspace.sharedWorkspace + .accessibilityDisplayShouldIncreaseContrast; break; case IntID::VideoDynamicRange: { - // If the platform says it supports HDR, then we claim to support video-dynamic-range. + // If the platform says it supports HDR, then we claim to support + // video-dynamic-range. gfxPlatform* platform = gfxPlatform::GetPlatform(); MOZ_ASSERT(platform); aResult = platform->SupportsHDR(); @@ -487,7 +515,8 @@ nsresult nsLookAndFeel::NativeGetFloat(FloatID aID, float& aResult) { aResult = 2.0f; break; case FloatID::CursorScale: { - id uaDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"com.apple.universalaccess"]; + id uaDefaults = [[NSUserDefaults alloc] + initWithSuiteName:@"com.apple.universalaccess"]; float f = [uaDefaults floatForKey:@"mouseDriverCursorSize"]; [uaDefaults release]; aResult = f > 0.0 ? f : 1.0; // default to 1.0 if value not available @@ -504,24 +533,29 @@ nsresult nsLookAndFeel::NativeGetFloat(FloatID aID, float& aResult) { } bool nsLookAndFeel::SystemWantsDarkTheme() { - // This returns true if the macOS system appearance is set to dark mode, false otherwise. - NSAppearanceName aquaOrDarkAqua = [NSApp.effectiveAppearance - bestMatchFromAppearancesWithNames:@[ NSAppearanceNameAqua, NSAppearanceNameDarkAqua ]]; + // This returns true if the macOS system appearance is set to dark mode, false + // otherwise. + NSAppearanceName aquaOrDarkAqua = + [NSApp.effectiveAppearance bestMatchFromAppearancesWithNames:@[ + NSAppearanceNameAqua, NSAppearanceNameDarkAqua + ]]; return [aquaOrDarkAqua isEqualToString:NSAppearanceNameDarkAqua]; } /*static*/ bool nsLookAndFeel::IsSystemOrientationRTL() { - NSWindow* window = [[NSWindow alloc] initWithContentRect:NSZeroRect - styleMask:NSWindowStyleMaskBorderless - backing:NSBackingStoreBuffered - defer:NO]; + NSWindow* window = + [[NSWindow alloc] initWithContentRect:NSZeroRect + styleMask:NSWindowStyleMaskBorderless + backing:NSBackingStoreBuffered + defer:NO]; auto direction = window.windowTitlebarLayoutDirection; [window release]; return direction == NSUserInterfaceLayoutDirectionRightToLeft; } -bool nsLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName, gfxFontStyle& aFontStyle) { +bool nsLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName, + gfxFontStyle& aFontStyle) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; nsAutoCString name; @@ -535,8 +569,10 @@ bool nsLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName, gfxFontStyle& void nsLookAndFeel::RecordAccessibilityTelemetry() { if ([[NSWorkspace sharedWorkspace] - respondsToSelector:@selector(accessibilityDisplayShouldInvertColors)]) { - bool val = [[NSWorkspace sharedWorkspace] accessibilityDisplayShouldInvertColors]; + respondsToSelector:@selector + (accessibilityDisplayShouldInvertColors)]) { + bool val = + [[NSWorkspace sharedWorkspace] accessibilityDisplayShouldInvertColors]; Telemetry::ScalarSet(Telemetry::ScalarID::A11Y_INVERT_COLORS, val); } } @@ -553,14 +589,16 @@ void nsLookAndFeel::RecordAccessibilityTelemetry() { - (instancetype)init { self = [super init]; - [NSNotificationCenter.defaultCenter addObserver:self - selector:@selector(colorsChanged) - name:NSControlTintDidChangeNotification - object:nil]; - [NSNotificationCenter.defaultCenter addObserver:self - selector:@selector(colorsChanged) - name:NSSystemColorsDidChangeNotification - object:nil]; + [NSNotificationCenter.defaultCenter + addObserver:self + selector:@selector(colorsChanged) + name:NSControlTintDidChangeNotification + object:nil]; + [NSNotificationCenter.defaultCenter + addObserver:self + selector:@selector(colorsChanged) + name:NSSystemColorsDidChangeNotification + object:nil]; [NSWorkspace.sharedWorkspace.notificationCenter addObserver:self @@ -568,10 +606,11 @@ void nsLookAndFeel::RecordAccessibilityTelemetry() { name:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification object:nil]; - [NSNotificationCenter.defaultCenter addObserver:self - selector:@selector(scrollbarsChanged) - name:NSPreferredScrollerStyleDidChangeNotification - object:nil]; + [NSNotificationCenter.defaultCenter + addObserver:self + selector:@selector(scrollbarsChanged) + name:NSPreferredScrollerStyleDidChangeNotification + object:nil]; [NSDistributedNotificationCenter.defaultCenter addObserver:self selector:@selector(scrollbarsChanged) @@ -595,7 +634,10 @@ void nsLookAndFeel::RecordAccessibilityTelemetry() { forKeyPath:@"effectiveAppearance" options:0 context:nil]; - [NSApp addObserver:self forKeyPath:@"effectiveAppearance" options:0 context:nil]; + [NSApp addObserver:self + forKeyPath:@"effectiveAppearance" + options:0 + context:nil]; return self; } @@ -607,7 +649,10 @@ void nsLookAndFeel::RecordAccessibilityTelemetry() { if ([keyPath isEqualToString:@"effectiveAppearance"]) { [self entireThemeChanged]; } else { - [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + [super observeValueForKeyPath:keyPath + ofObject:object + change:change + context:context]; } } @@ -620,11 +665,12 @@ void nsLookAndFeel::RecordAccessibilityTelemetry() { } - (void)mediaQueriesChanged { - // Changing`Invert Colors` sends AccessibilityDisplayOptionsDidChangeNotifications. - // We monitor that setting via telemetry, so call into that - // recording method here. + // Changing`Invert Colors` sends + // AccessibilityDisplayOptionsDidChangeNotifications. We monitor that setting + // via telemetry, so call into that recording method here. nsLookAndFeel::RecordAccessibilityTelemetry(); - LookAndFeel::NotifyChangedAllWindows(widget::ThemeChangeKind::MediaQueriesOnly); + LookAndFeel::NotifyChangedAllWindows( + widget::ThemeChangeKind::MediaQueriesOnly); } - (void)colorsChanged { @@ -632,9 +678,12 @@ void nsLookAndFeel::RecordAccessibilityTelemetry() { } - (void)cachedValuesChanged { - // We only need to re-cache (and broadcast) updated LookAndFeel values, so that they're - // up-to-date the next time they're queried. No further change handling is needed. - // TODO: Add a change hint for this which avoids the unnecessary media query invalidation. - LookAndFeel::NotifyChangedAllWindows(widget::ThemeChangeKind::MediaQueriesOnly); + // We only need to re-cache (and broadcast) updated LookAndFeel values, so + // that they're up-to-date the next time they're queried. No further change + // handling is needed. + // TODO: Add a change hint for this which avoids the unnecessary media query + // invalidation. + LookAndFeel::NotifyChangedAllWindows( + widget::ThemeChangeKind::MediaQueriesOnly); } @end diff --git a/widget/cocoa/nsMacCursor.mm b/widget/cocoa/nsMacCursor.mm index 0f56cf9a2793..c4dda5acabf1 100644 --- a/widget/cocoa/nsMacCursor.mm +++ b/widget/cocoa/nsMacCursor.mm @@ -12,9 +12,9 @@ /*! @category nsMacCursor (PrivateMethods) @abstract Private methods internal to the nsMacCursor class. - @discussion nsMacCursor is effectively an abstract class. It does not define - complete behaviour in and of itself, the subclasses defined in this file provide the useful - implementations. + @discussion nsMacCursor is effectively an abstract class. It + does not define complete behaviour in and of itself, the subclasses defined + in this file provide the useful implementations. */ @interface nsMacCursor (PrivateMethods) @@ -27,56 +27,62 @@ /*! @method numFrames @abstract Query the number of frames in this cursor's animation. - @discussion Returns the number of frames in this cursor's animation. Static cursors return 1. + @discussion Returns the number of frames in this cursor's animation. Static + cursors return 1. */ - (int)numFrames; /*! @method createTimer @abstract Create a Timer to use to animate the cursor. - @discussion Creates an instance of NSTimer which is used to drive the cursor - animation. This method should only be called for cursors that are animated. + @discussion Creates an instance of NSTimer which is used to + drive the cursor animation. This method should only be called for cursors + that are animated. */ - (void)createTimer; /*! @method destroyTimer @abstract Destroy any timer instance associated with this cursor. - @discussion Invalidates and releases any NSTimer instance associated with this - cursor. + @discussion Invalidates and releases any NSTimer instance + associated with this cursor. */ - (void)destroyTimer; /*! @method destroyTimer @abstract Destroy any timer instance associated with this cursor. - @discussion Invalidates and releases any NSTimer instance associated with this - cursor. + @discussion Invalidates and releases any NSTimer instance + associated with this cursor. */ /*! @method advanceAnimatedCursor: @abstract Method called by animation timer to perform animation. - @discussion Called by an animated cursor's associated timer to advance the animation to the next - frame. Determines which frame should occur next and sets the cursor to that frame. + @discussion Called by an animated cursor's associated timer to advance the + animation to the next frame. Determines which frame should occur next and + sets the cursor to that frame. @param aTimer the timer causing the animation */ - (void)advanceAnimatedCursor:(NSTimer*)aTimer; /*! @method setFrame: - @abstract Sets the current cursor, using an index to determine which frame in the animation to - display. - @discussion Sets the current cursor. The frame index determines which frame is shown if the - cursor is animated. Frames and numbered from 0 to -[nsMacCursor numFrames] - - 1. A static cursor has a single frame, numbered 0. - @param aFrameIndex the index indicating which frame from the animation to display + @abstract Sets the current cursor, using an index to determine which frame + in the animation to display. + @discussion Sets the current cursor. The frame index determines which frame + is shown if the cursor is animated. Frames and numbered from 0 + to -[nsMacCursor numFrames] - 1. A static cursor has a single + frame, numbered 0. + @param aFrameIndex the index indicating which frame from the animation + to display */ - (void)setFrame:(int)aFrameIndex; @end /*! @class nsCocoaCursor - @abstract Implementation of nsMacCursor that uses Cocoa NSCursor - instances. - @discussion Displays a static or animated cursor, using Cocoa NSCursor instances. - These can be either built-in NSCursor instances, or custom NSCursors - created from images. When more than one NSCursor is provided, the cursor will use - these as animation frames. + @abstract Implementation of nsMacCursor that uses Cocoa + NSCursor instances. + @discussion Displays a static or animated cursor, using Cocoa + NSCursor instances. These can be either built-in + NSCursor instances, or custom NSCursors created + from images. When more than one NSCursor is provided, the cursor + will use these as animation frames. */ @interface nsCocoaCursor : nsMacCursor { @private @@ -85,13 +91,16 @@ } /*! @method initWithFrames: - @abstract Create an animated cursor by specifying the frames to use for the animation. - @discussion Creates a cursor that will animate by cycling through the given frames. Each element - of the array must be an instance of NSCursor - @param aCursorFrames an array of NSCursor, representing the frames of an - animated cursor, in the order they should be played. + @abstract Create an animated cursor by specifying the frames to use for + the animation. + @discussion Creates a cursor that will animate by cycling through the given + frames. Each element of the array must be an instance of + NSCursor + @param aCursorFrames an array of NSCursor, representing + the frames of an animated cursor, in the order they should be played. @param aType the corresponding nsCursor constant - @result an instance of nsCocoaCursor that will animate the given cursor frames + @result an instance of nsCocoaCursor that will animate the + given cursor frames */ - (id)initWithFrames:(NSArray*)aCursorFrames type:(nsCursor)aType; @@ -106,18 +115,22 @@ - (id)initWithCursor:(NSCursor*)aCursor type:(nsCursor)aType; /*! @method initWithImageNamed:hotSpot: - @abstract Create a cursor by specifying the name of an image resource to use for the cursor - and a hotspot. - @discussion Creates a cursor by loading the named image using the +[NSImage - imageNamed:] method.

The image must be compatible with any restrictions laid down by - NSCursor. These vary by operating system version.

The hotspot precisely - determines the point where the user clicks when using the cursor.

+ @abstract Create a cursor by specifying the name of an image resource to + use for the cursor and a hotspot. + @discussion Creates a cursor by loading the named image using the + +[NSImage imageNamed:] method.

The image must be compatible + with any restrictions laid down by NSCursor. These vary by + operating system version.

The hotspot precisely determines the point + where the user clicks when using the cursor.

@param aCursor the name of the image to use for the cursor @param aPoint the point within the cursor to use as the hotspot @param aType the corresponding nsCursor constant - @result an instance of nsCocoaCursor that uses the given image and hotspot + @result an instance of nsCocoaCursor that uses the given + image and hotspot */ -- (id)initWithImageNamed:(NSString*)aCursorImage hotSpot:(NSPoint)aPoint type:(nsCursor)aType; +- (id)initWithImageNamed:(NSString*)aCursorImage + hotSpot:(NSPoint)aPoint + type:(nsCursor)aType; @end @@ -126,7 +139,8 @@ + (nsMacCursor*)cursorWithCursor:(NSCursor*)aCursor type:(nsCursor)aType { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - return [[[nsCocoaCursor alloc] initWithCursor:aCursor type:aType] autorelease]; + return [[[nsCocoaCursor alloc] initWithCursor:aCursor + type:aType] autorelease]; NS_OBJC_END_TRY_BLOCK_RETURN(nil); } @@ -136,7 +150,8 @@ type:(nsCursor)aType { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - return [[[nsCocoaCursor alloc] initWithImageNamed:aCursorImage hotSpot:aPoint + return [[[nsCocoaCursor alloc] initWithImageNamed:aCursorImage + hotSpot:aPoint type:aType] autorelease]; NS_OBJC_END_TRY_BLOCK_RETURN(nil); @@ -145,12 +160,14 @@ + (nsMacCursor*)cursorWithFrames:(NSArray*)aCursorFrames type:(nsCursor)aType { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - return [[[nsCocoaCursor alloc] initWithFrames:aCursorFrames type:aType] autorelease]; + return [[[nsCocoaCursor alloc] initWithFrames:aCursorFrames + type:aType] autorelease]; NS_OBJC_END_TRY_BLOCK_RETURN(nil); } -+ (NSCursor*)cocoaCursorWithImageNamed:(NSString*)imageName hotSpot:(NSPoint)aPoint { ++ (NSCursor*)cocoaCursorWithImageNamed:(NSString*)imageName + hotSpot:(NSPoint)aPoint { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; nsCOMPtr resDir; @@ -174,22 +191,26 @@ pathToImage = [pathToImage stringByAppendingPathExtension:@"png"]; pathToHiDpiImage = [pathToHiDpiImage stringByAppendingPathExtension:@"png"]; - cursorImage = [[[NSImage alloc] initWithContentsOfFile:pathToImage] autorelease]; + cursorImage = + [[[NSImage alloc] initWithContentsOfFile:pathToImage] autorelease]; if (!cursorImage) goto INIT_FAILURE; // Note 1: There are a few different ways to get a hidpi image via // initWithContentsOfFile. We let the OS handle this here: when the // file basename ends in "@2x", it will be displayed at native resolution - // instead of being pixel-doubled. See bug 784909 comment 7 for alternates ways. + // instead of being pixel-doubled. See bug 784909 comment 7 for alternates + // ways. // // Note 2: The OS is picky, and will ignore the hidpi representation // unless it is exactly twice the size of the lowdpi image. - hiDpiCursorImage = [[[NSImage alloc] initWithContentsOfFile:pathToHiDpiImage] autorelease]; + hiDpiCursorImage = + [[[NSImage alloc] initWithContentsOfFile:pathToHiDpiImage] autorelease]; if (hiDpiCursorImage) { NSImageRep* imageRep = [[hiDpiCursorImage representations] objectAtIndex:0]; [cursorImage addRepresentation:imageRep]; } - return [[[NSCursor alloc] initWithImage:cursorImage hotSpot:aPoint] autorelease]; + return [[[NSCursor alloc] initWithImage:cursorImage + hotSpot:aPoint] autorelease]; INIT_FAILURE: NS_WARNING("Problem getting path to cursor image file!"); @@ -236,11 +257,12 @@ INIT_FAILURE: NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; if (!mTimer) { - mTimer = [[NSTimer scheduledTimerWithTimeInterval:0.25 - target:self - selector:@selector(advanceAnimatedCursor:) - userInfo:nil - repeats:YES] retain]; + mTimer = [[NSTimer + scheduledTimerWithTimeInterval:0.25 + target:self + selector:@selector(advanceAnimatedCursor:) + userInfo:nil + repeats:YES] retain]; } NS_OBJC_END_TRY_IGNORE_BLOCK; @@ -316,11 +338,15 @@ INIT_FAILURE: NS_OBJC_END_TRY_BLOCK_RETURN(nil); } -- (id)initWithImageNamed:(NSString*)aCursorImage hotSpot:(NSPoint)aPoint type:(nsCursor)aType { +- (id)initWithImageNamed:(NSString*)aCursorImage + hotSpot:(NSPoint)aPoint + type:(nsCursor)aType { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - return [self initWithCursor:[nsMacCursor cocoaCursorWithImageNamed:aCursorImage hotSpot:aPoint] - type:aType]; + return + [self initWithCursor:[nsMacCursor cocoaCursorWithImageNamed:aCursorImage + hotSpot:aPoint] + type:aType]; NS_OBJC_END_TRY_BLOCK_RETURN(nil); } diff --git a/widget/cocoa/nsMacDockSupport.mm b/widget/cocoa/nsMacDockSupport.mm index 9614558ec915..5e9da63e10c9 100644 --- a/widget/cocoa/nsMacDockSupport.mm +++ b/widget/cocoa/nsMacDockSupport.mm @@ -32,7 +32,8 @@ NS_IMPL_ISUPPORTS(nsMacDockSupport, nsIMacDockSupport, nsITaskbarProgress) @synthesize fractionValue = mFractionValue; - (void)drawRect:(NSRect)aRect { - // Erase the background behind this view, i.e. cut a rectangle hole in the icon. + // Erase the background behind this view, i.e. cut a rectangle hole in the + // icon. [[NSColor clearColor] set]; NSRectFill(self.bounds); @@ -103,7 +104,8 @@ NS_IMETHODIMP nsMacDockSupport::ActivateApplication(bool aIgnoreOtherApplications) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - [[NSApplication sharedApplication] activateIgnoringOtherApps:aIgnoreOtherApplications]; + [[NSApplication sharedApplication] + activateIgnoringOtherApps:aIgnoreOtherApplications]; return NS_OK; NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); @@ -118,9 +120,11 @@ nsMacDockSupport::SetBadgeText(const nsAString& aBadgeText) { if (aBadgeText.IsEmpty()) [tile setBadgeLabel:nil]; else - [tile setBadgeLabel:[NSString - stringWithCharacters:reinterpret_cast(mBadgeText.get()) - length:mBadgeText.Length()]]; + [tile + setBadgeLabel:[NSString + stringWithCharacters:reinterpret_cast( + mBadgeText.get()) + length:mBadgeText.Length()]]; return NS_OK; NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); @@ -133,8 +137,8 @@ nsMacDockSupport::GetBadgeText(nsAString& aBadgeText) { } NS_IMETHODIMP -nsMacDockSupport::SetProgressState(nsTaskbarProgressState aState, uint64_t aCurrentValue, - uint64_t aMaxValue) { +nsMacDockSupport::SetProgressState(nsTaskbarProgressState aState, + uint64_t aCurrentValue, uint64_t aMaxValue) { NS_ENSURE_ARG_RANGE(aState, 0, STATE_PAUSED); if (aState == STATE_NO_PROGRESS || aState == STATE_INDETERMINATE) { NS_ENSURE_TRUE(aCurrentValue == 0, NS_ERROR_INVALID_ARG); @@ -162,22 +166,26 @@ nsresult nsMacDockSupport::UpdateDockTile() { // Create the following NSView hierarchy: // * mDockTileWrapperView (NSView) // * imageView (NSImageView) <- has the application icon - // * mProgressDockOverlayView (MOZProgressDockOverlayView) <- draws the progress bar + // * mProgressDockOverlayView (MOZProgressDockOverlayView) <- draws the + // progress bar - mDockTileWrapperView = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 32, 32)]; - mDockTileWrapperView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; + mDockTileWrapperView = + [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 32, 32)]; + mDockTileWrapperView.autoresizingMask = + NSViewWidthSizable | NSViewHeightSizable; - NSImageView* imageView = [[NSImageView alloc] initWithFrame:[mDockTileWrapperView bounds]]; + NSImageView* imageView = + [[NSImageView alloc] initWithFrame:[mDockTileWrapperView bounds]]; imageView.image = [NSImage imageNamed:@"NSApplicationIcon"]; imageView.imageScaling = NSImageScaleAxesIndependently; imageView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; [mDockTileWrapperView addSubview:imageView]; - mProgressDockOverlayView = - [[MOZProgressDockOverlayView alloc] initWithFrame:NSMakeRect(1, 3, 30, 4)]; - mProgressDockOverlayView.autoresizingMask = NSViewMinXMargin | NSViewWidthSizable | - NSViewMaxXMargin | NSViewMinYMargin | - NSViewHeightSizable | NSViewMaxYMargin; + mProgressDockOverlayView = [[MOZProgressDockOverlayView alloc] + initWithFrame:NSMakeRect(1, 3, 30, 4)]; + mProgressDockOverlayView.autoresizingMask = + NSViewMinXMargin | NSViewWidthSizable | NSViewMaxXMargin | + NSViewMinYMargin | NSViewHeightSizable | NSViewMaxYMargin; [mDockTileWrapperView addSubview:mProgressDockOverlayView]; } if (NSApp.dockTile.contentView != mDockTileWrapperView) { @@ -205,21 +213,23 @@ nsresult nsMacDockSupport::UpdateDockTile() { extern "C" { // Private CFURL API used by the Dock. CFPropertyListRef _CFURLCopyPropertyListRepresentation(CFURLRef url); -CFURLRef _CFURLCreateFromPropertyListRepresentation(CFAllocatorRef alloc, - CFPropertyListRef pListRepresentation); +CFURLRef _CFURLCreateFromPropertyListRepresentation( + CFAllocatorRef alloc, CFPropertyListRef pListRepresentation); } // extern "C" namespace { -const NSArray* const browserAppNames = - [NSArray arrayWithObjects:@"Firefox.app", @"Firefox Beta.app", @"Firefox Nightly.app", - @"Safari.app", @"WebKit.app", @"Google Chrome.app", - @"Google Chrome Canary.app", @"Chromium.app", @"Opera.app", nil]; +const NSArray* const browserAppNames = [NSArray + arrayWithObjects:@"Firefox.app", @"Firefox Beta.app", + @"Firefox Nightly.app", @"Safari.app", @"WebKit.app", + @"Google Chrome.app", @"Google Chrome Canary.app", + @"Chromium.app", @"Opera.app", nil]; constexpr NSString* const kDockDomainName = @"com.apple.dock"; // See https://developer.apple.com/documentation/devicemanagement/dock constexpr NSString* const kDockPersistentAppsKey = @"persistent-apps"; -// See https://developer.apple.com/documentation/devicemanagement/dock/staticitem +// See +// https://developer.apple.com/documentation/devicemanagement/dock/staticitem constexpr NSString* const kDockTileDataKey = @"tile-data"; constexpr NSString* const kDockFileDataKey = @"file-data"; @@ -247,7 +257,8 @@ NSString* GetPathForApp(NSDictionary* aPersistantApp) { // Some special tiles may not have DockFileData but we can ignore those. return nil; } - NSURL* url = CFBridgingRelease(_CFURLCreateFromPropertyListRepresentation(NULL, fileData)); + NSURL* url = CFBridgingRelease( + _CFURLCreateFromPropertyListRepresentation(NULL, fileData)); if (!url) { return nil; } @@ -257,7 +268,8 @@ NSString* GetPathForApp(NSDictionary* aPersistantApp) { // The only reliable way to get our changes to take effect seems to be to use // `kill`. void RefreshDock(NSDictionary* aDockPlist) { - [[NSUserDefaults standardUserDefaults] setPersistentDomain:aDockPlist forName:kDockDomainName]; + [[NSUserDefaults standardUserDefaults] setPersistentDomain:aDockPlist + forName:kDockDomainName]; NSRunningApplication* dockApp = [[NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.dock"] firstObject]; if (!dockApp) { @@ -276,8 +288,8 @@ nsresult nsMacDockSupport::GetIsAppInDock(bool* aIsInDock) { *aIsInDock = false; - NSDictionary* dockPlist = - [[NSUserDefaults standardUserDefaults] persistentDomainForName:kDockDomainName]; + NSDictionary* dockPlist = [[NSUserDefaults standardUserDefaults] + persistentDomainForName:kDockDomainName]; if (!dockPlist) { return NS_ERROR_FAILURE; } @@ -302,22 +314,22 @@ nsresult nsMacDockSupport::GetIsAppInDock(bool* aIsInDock) { NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -nsresult nsMacDockSupport::EnsureAppIsPinnedToDock(const nsAString& aAppPath, - const nsAString& aAppToReplacePath, - bool* aIsInDock) { +nsresult nsMacDockSupport::EnsureAppIsPinnedToDock( + const nsAString& aAppPath, const nsAString& aAppToReplacePath, + bool* aIsInDock) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; MOZ_ASSERT(aAppPath != aAppToReplacePath || !aAppPath.IsEmpty()); *aIsInDock = false; - NSString* appPath = - !aAppPath.IsEmpty() ? nsCocoaUtils::ToNSString(aAppPath) : [[NSBundle mainBundle] bundlePath]; + NSString* appPath = !aAppPath.IsEmpty() ? nsCocoaUtils::ToNSString(aAppPath) + : [[NSBundle mainBundle] bundlePath]; NSString* appToReplacePath = nsCocoaUtils::ToNSString(aAppToReplacePath); - NSMutableDictionary* dockPlist = - [NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] - persistentDomainForName:kDockDomainName]]; + NSMutableDictionary* dockPlist = [NSMutableDictionary + dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] + persistentDomainForName:kDockDomainName]]; if (!dockPlist) { return NS_ERROR_FAILURE; } @@ -335,11 +347,13 @@ nsresult nsMacDockSupport::EnsureAppIsPinnedToDock(const nsAString& aAppPath, NSUInteger toReplaceAppIndex = NSNotFound; NSUInteger lastBrowserAppIndex = NSNotFound; for (NSUInteger index = 0; index < [persistentApps count]; ++index) { - NSString* persistentAppPath = GetPathForApp([persistentApps objectAtIndex:index]); + NSString* persistentAppPath = + GetPathForApp([persistentApps objectAtIndex:index]); if ([persistentAppPath isEqualToString:appPath]) { preexistingAppIndex = index; - } else if (appToReplacePath && [persistentAppPath isEqualToString:appToReplacePath]) { + } else if (appToReplacePath && + [persistentAppPath isEqualToString:appToReplacePath]) { toReplaceAppIndex = index; } else { NSString* appName = [appPath lastPathComponent]; @@ -381,14 +395,16 @@ nsresult nsMacDockSupport::EnsureAppIsPinnedToDock(const nsAString& aAppPath, NSDictionary* newDockTile = nullptr; { NSURL* appUrl = [NSURL fileURLWithPath:appPath isDirectory:YES]; - NSDictionary* dict = - CFBridgingRelease(_CFURLCopyPropertyListRepresentation((__bridge CFURLRef)appUrl)); + NSDictionary* dict = CFBridgingRelease( + _CFURLCopyPropertyListRepresentation((__bridge CFURLRef)appUrl)); if (!dict) { return NS_ERROR_FAILURE; } - NSDictionary* dockTileData = [NSDictionary dictionaryWithObject:dict forKey:kDockFileDataKey]; + NSDictionary* dockTileData = + [NSDictionary dictionaryWithObject:dict forKey:kDockFileDataKey]; if (dockTileData) { - newDockTile = [NSDictionary dictionaryWithObject:dockTileData forKey:kDockTileDataKey]; + newDockTile = [NSDictionary dictionaryWithObject:dockTileData + forKey:kDockTileDataKey]; } if (!newDockTile) { return NS_ERROR_FAILURE; @@ -397,7 +413,8 @@ nsresult nsMacDockSupport::EnsureAppIsPinnedToDock(const nsAString& aAppPath, // Update the Dock: if (toReplaceAppIndex != NSNotFound) { - [persistentApps replaceObjectAtIndex:toReplaceAppIndex withObject:newDockTile]; + [persistentApps replaceObjectAtIndex:toReplaceAppIndex + withObject:newDockTile]; } else { NSUInteger index; if (sameNameAppIndex != NSNotFound) { diff --git a/widget/cocoa/nsMacFinderProgress.mm b/widget/cocoa/nsMacFinderProgress.mm index 2e518fe0122a..e2b0401313e8 100644 --- a/widget/cocoa/nsMacFinderProgress.mm +++ b/widget/cocoa/nsMacFinderProgress.mm @@ -1,4 +1,5 @@ -/* -*- Mode: Objective-C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: Objective-C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: + * 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this @@ -24,16 +25,19 @@ nsMacFinderProgress::~nsMacFinderProgress() { } NS_IMETHODIMP -nsMacFinderProgress::Init(const nsAString& path, - nsIMacFinderProgressCanceledCallback* cancellationCallback) { +nsMacFinderProgress::Init( + const nsAString& path, + nsIMacFinderProgressCanceledCallback* cancellationCallback) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; NSURL* pathUrl = [NSURL fileURLWithPath:[NSString - stringWithCharacters:reinterpret_cast(path.BeginReading()) + stringWithCharacters:reinterpret_cast( + path.BeginReading()) length:path.Length()]]; NSDictionary* userInfo = @{ - @"NSProgressFileOperationKindKey" : @"NSProgressFileOperationKindDownloading", + @"NSProgressFileOperationKindKey" : + @"NSProgressFileOperationKindDownloading", @"NSProgressFileURLKey" : pathUrl }; @@ -41,13 +45,14 @@ nsMacFinderProgress::Init(const nsAString& path, mProgress.kind = NSProgressKindFile; mProgress.cancellable = YES; - nsMainThreadPtrHandle cancellationCallbackHandle( - new nsMainThreadPtrHolder( - "MacFinderProgress::CancellationCallback", cancellationCallback)); + nsMainThreadPtrHandle + cancellationCallbackHandle( + new nsMainThreadPtrHolder( + "MacFinderProgress::CancellationCallback", cancellationCallback)); mProgress.cancellationHandler = ^{ - NS_DispatchToMainThread( - NS_NewRunnableFunction("MacFinderProgress::Canceled", [cancellationCallbackHandle] { + NS_DispatchToMainThread(NS_NewRunnableFunction( + "MacFinderProgress::Canceled", [cancellationCallbackHandle] { MOZ_ASSERT(NS_IsMainThread()); cancellationCallbackHandle->Canceled(); })); @@ -61,7 +66,8 @@ nsMacFinderProgress::Init(const nsAString& path, } NS_IMETHODIMP -nsMacFinderProgress::UpdateProgress(uint64_t currentProgress, uint64_t totalProgress) { +nsMacFinderProgress::UpdateProgress(uint64_t currentProgress, + uint64_t totalProgress) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; if (mProgress) { mProgress.totalUnitCount = totalProgress; diff --git a/widget/cocoa/nsMacSharingService.mm b/widget/cocoa/nsMacSharingService.mm index bc62e5e85e55..d70433bc7b37 100644 --- a/widget/cocoa/nsMacSharingService.mm +++ b/widget/cocoa/nsMacSharingService.mm @@ -15,11 +15,13 @@ NS_IMPL_ISUPPORTS(nsMacSharingService, nsIMacSharingService) -NSString* const remindersServiceName = @"com.apple.reminders.RemindersShareExtension"; +NSString* const remindersServiceName = + @"com.apple.reminders.RemindersShareExtension"; // These are some undocumented constants also used by Safari // to let us open the preferences window -NSString* const extensionPrefPanePath = @"/System/Library/PreferencePanes/Extensions.prefPane"; +NSString* const extensionPrefPanePath = + @"/System/Library/PreferencePanes/Extensions.prefPane"; const UInt32 openSharingSubpaneDescriptorType = 'ptru'; NSString* const openSharingSubpaneActionKey = @"action"; NSString* const openSharingSubpaneActionValue = @"revealExtensionPoint"; @@ -31,10 +33,11 @@ NSString* const openSharingSubpaneProtocolValue = @"com.apple.share-services"; - (id)name; @end -// Filter providers that we do not want to expose to the user, because they are duplicates or do not -// work correctly within the context +// Filter providers that we do not want to expose to the user, because they are +// duplicates or do not work correctly within the context static bool ShouldIgnoreProvider(NSString* aProviderName) { - return [aProviderName isEqualToString:@"com.apple.share.System.add-to-safari-reading-list"]; + return [aProviderName + isEqualToString:@"com.apple.share.System.add-to-safari-reading-list"]; } // Clean up the activity once the share is complete @@ -61,7 +64,8 @@ static bool ShouldIgnoreProvider(NSString* aProviderName) { mShareActivity = nil; } -- (void)sharingService:(NSSharingService*)sharingService didShareItems:(NSArray*)items { +- (void)sharingService:(NSSharingService*)sharingService + didShareItems:(NSArray*)items { [self cleanup]; } @@ -80,16 +84,18 @@ static bool ShouldIgnoreProvider(NSString* aProviderName) { static NSString* NSImageToBase64(const NSImage* aImage) { CGImageRef cgRef = [aImage CGImageForProposedRect:nil context:nil hints:nil]; - NSBitmapImageRep* bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:cgRef]; + NSBitmapImageRep* bitmapRep = + [[NSBitmapImageRep alloc] initWithCGImage:cgRef]; [bitmapRep setSize:[aImage size]]; - NSData* imageData = [bitmapRep representationUsingType:NSPNGFileType properties:@{}]; + NSData* imageData = [bitmapRep representationUsingType:NSPNGFileType + properties:@{}]; NSString* base64Encoded = [imageData base64EncodedStringWithOptions:0]; [bitmapRep release]; return [NSString stringWithFormat:@"data:image/png;base64,%@", base64Encoded]; } -static void SetStrAttribute(JSContext* aCx, JS::Rooted& aObj, const char* aKey, - NSString* aVal) { +static void SetStrAttribute(JSContext* aCx, JS::Rooted& aObj, + const char* aKey, NSString* aVal) { nsAutoString strVal; mozilla::CopyCocoaStringToXPCOMString(aVal, strVal); JS::Rooted title(aCx, JS_NewUCStringCopyZ(aCx, strVal.get())); @@ -97,8 +103,9 @@ static void SetStrAttribute(JSContext* aCx, JS::Rooted& aObj, const c JS_SetProperty(aCx, aObj, aKey, attVal); } -nsresult nsMacSharingService::GetSharingProviders(const nsAString& aPageUrl, JSContext* aCx, - JS::MutableHandle aResult) { +nsresult nsMacSharingService::GetSharingProviders( + const nsAString& aPageUrl, JSContext* aCx, + JS::MutableHandle aResult) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; NSURL* url = nsCocoaUtils::ToNSURL(aPageUrl); @@ -135,18 +142,20 @@ NS_IMETHODIMP nsMacSharingService::OpenSharingPreferences() { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - NSURL* prefPaneURL = [NSURL fileURLWithPath:extensionPrefPanePath isDirectory:YES]; + NSURL* prefPaneURL = [NSURL fileURLWithPath:extensionPrefPanePath + isDirectory:YES]; NSDictionary* args = @{ openSharingSubpaneActionKey : openSharingSubpaneActionValue, openSharingSubpaneProtocolKey : openSharingSubpaneProtocolValue }; - NSData* data = [NSPropertyListSerialization dataWithPropertyList:args - format:NSPropertyListXMLFormat_v1_0 - options:0 - error:nil]; - NSAppleEventDescriptor* descriptor = - [[NSAppleEventDescriptor alloc] initWithDescriptorType:openSharingSubpaneDescriptorType - data:data]; + NSData* data = [NSPropertyListSerialization + dataWithPropertyList:args + format:NSPropertyListXMLFormat_v1_0 + options:0 + error:nil]; + NSAppleEventDescriptor* descriptor = [[NSAppleEventDescriptor alloc] + initWithDescriptorType:openSharingSubpaneDescriptorType + data:data]; [[NSWorkspace sharedWorkspace] openURLs:@[ prefPaneURL ] withAppBundleIdentifier:nil @@ -161,19 +170,21 @@ nsMacSharingService::OpenSharingPreferences() { } NS_IMETHODIMP -nsMacSharingService::ShareUrl(const nsAString& aServiceName, const nsAString& aPageUrl, +nsMacSharingService::ShareUrl(const nsAString& aServiceName, + const nsAString& aPageUrl, const nsAString& aPageTitle) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; NSString* serviceName = nsCocoaUtils::ToNSString(aServiceName); NSURL* pageUrl = nsCocoaUtils::ToNSURL(aPageUrl); NSString* pageTitle = nsCocoaUtils::ToNSString(aPageTitle); - NSSharingService* service = [NSSharingService sharingServiceNamed:serviceName]; + NSSharingService* service = + [NSSharingService sharingServiceNamed:serviceName]; // Reminders fetch its data from an activity, not the share data if ([[service name] isEqual:remindersServiceName]) { - NSUserActivity* shareActivity = - [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb]; + NSUserActivity* shareActivity = [[NSUserActivity alloc] + initWithActivityType:NSUserActivityTypeBrowsingWeb]; if ([pageUrl.scheme hasPrefix:@"http"]) { [shareActivity setWebpageURL:pageUrl]; diff --git a/widget/cocoa/nsMacUserActivityUpdater.mm b/widget/cocoa/nsMacUserActivityUpdater.mm index cc80e1259b46..9fedb618a4eb 100644 --- a/widget/cocoa/nsMacUserActivityUpdater.mm +++ b/widget/cocoa/nsMacUserActivityUpdater.mm @@ -13,7 +13,8 @@ NS_IMPL_ISUPPORTS(nsMacUserActivityUpdater, nsIMacUserActivityUpdater) NS_IMETHODIMP -nsMacUserActivityUpdater::UpdateLocation(const nsAString& aPageUrl, const nsAString& aPageTitle, +nsMacUserActivityUpdater::UpdateLocation(const nsAString& aPageUrl, + const nsAString& aPageTitle, nsIBaseWindow* aWindow) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; if (gfxPlatform::IsHeadless()) { @@ -27,8 +28,8 @@ nsMacUserActivityUpdater::UpdateLocation(const nsAString& aPageUrl, const nsAStr } NSURL* pageUrl = nsCocoaUtils::ToNSURL(aPageUrl); - if (!pageUrl || - (![pageUrl.scheme isEqualToString:@"https"] && ![pageUrl.scheme isEqualToString:@"http"])) { + if (!pageUrl || (![pageUrl.scheme isEqualToString:@"https"] && + ![pageUrl.scheme isEqualToString:@"http"])) { [cocoaWin.userActivity invalidate]; return NS_OK; } @@ -38,8 +39,8 @@ nsMacUserActivityUpdater::UpdateLocation(const nsAString& aPageUrl, const nsAStr pageTitle = pageUrl.absoluteString; } - NSUserActivity* userActivity = - [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb]; + NSUserActivity* userActivity = [[NSUserActivity alloc] + initWithActivityType:NSUserActivityTypeBrowsingWeb]; userActivity.webpageURL = pageUrl; userActivity.title = pageTitle; cocoaWin.userActivity = userActivity; diff --git a/widget/cocoa/nsMacWebAppUtils.mm b/widget/cocoa/nsMacWebAppUtils.mm index 909854472462..e1a06f873d6e 100644 --- a/widget/cocoa/nsMacWebAppUtils.mm +++ b/widget/cocoa/nsMacWebAppUtils.mm @@ -13,25 +13,28 @@ #include "nsObjCExceptions.h" // Find the path to the app with the given bundleIdentifier, if any. -// Note that the OS will return the path to the newest binary, if there is more than one. -// The determination of 'newest' is complex and beyond the scope of this comment. +// Note that the OS will return the path to the newest binary, if there is more +// than one. The determination of 'newest' is complex and beyond the scope of +// this comment. NS_IMPL_ISUPPORTS(nsMacWebAppUtils, nsIMacWebAppUtils) -NS_IMETHODIMP nsMacWebAppUtils::PathForAppWithIdentifier(const nsAString& bundleIdentifier, - nsAString& outPath) { +NS_IMETHODIMP nsMacWebAppUtils::PathForAppWithIdentifier( + const nsAString& bundleIdentifier, nsAString& outPath) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; outPath.Truncate(); nsAutoreleasePool localPool; - // note that the result of this expression might be nil, meaning no matching app was found. + // note that the result of this expression might be nil, meaning no matching + // app was found. NSString* temp = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier: - [NSString stringWithCharacters:reinterpret_cast( - ((nsString)bundleIdentifier).get()) - length:((nsString)bundleIdentifier).Length()]]; + [NSString + stringWithCharacters:reinterpret_cast( + ((nsString)bundleIdentifier).get()) + length:((nsString)bundleIdentifier).Length()]]; if (temp) { // Copy out the resultant absolute path into outPath if non-nil. @@ -43,18 +46,20 @@ NS_IMETHODIMP nsMacWebAppUtils::PathForAppWithIdentifier(const nsAString& bundle NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -NS_IMETHODIMP nsMacWebAppUtils::LaunchAppWithIdentifier(const nsAString& bundleIdentifier) { +NS_IMETHODIMP nsMacWebAppUtils::LaunchAppWithIdentifier( + const nsAString& bundleIdentifier) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; nsAutoreleasePool localPool; - // Note this might return false, meaning the app wasnt launched for some reason. + // Note this might return false, meaning the app wasnt launched for some + // reason. BOOL success = [[NSWorkspace sharedWorkspace] - launchAppWithBundleIdentifier:[NSString - stringWithCharacters:reinterpret_cast( - ((nsString)bundleIdentifier) - .get()) - length:((nsString)bundleIdentifier).Length()] + launchAppWithBundleIdentifier: + [NSString + stringWithCharacters:reinterpret_cast( + ((nsString)bundleIdentifier).get()) + length:((nsString)bundleIdentifier).Length()] options:(NSWorkspaceLaunchOptions)0 additionalEventParamDescriptor:nil launchIdentifier:NULL]; @@ -64,7 +69,8 @@ NS_IMETHODIMP nsMacWebAppUtils::LaunchAppWithIdentifier(const nsAString& bundleI NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -NS_IMETHODIMP nsMacWebAppUtils::TrashApp(const nsAString& path, nsITrashAppCallback* aCallback) { +NS_IMETHODIMP nsMacWebAppUtils::TrashApp(const nsAString& path, + nsITrashAppCallback* aCallback) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; if (NS_WARN_IF(!aCallback)) { @@ -74,11 +80,13 @@ NS_IMETHODIMP nsMacWebAppUtils::TrashApp(const nsAString& path, nsITrashAppCallb nsCOMPtr callback = aCallback; NSString* tempString = - [NSString stringWithCharacters:reinterpret_cast(((nsString)path).get()) + [NSString stringWithCharacters:reinterpret_cast( + ((nsString)path).get()) length:path.Length()]; [[NSWorkspace sharedWorkspace] - recycleURLs:[NSArray arrayWithObject:[NSURL fileURLWithPath:tempString]] + recycleURLs:[NSArray + arrayWithObject:[NSURL fileURLWithPath:tempString]] completionHandler:^(NSDictionary* newURLs, NSError* error) { nsresult rv = (error == nil) ? NS_OK : NS_ERROR_FAILURE; callback->TrashAppFinished(rv); diff --git a/widget/cocoa/nsMenuBarX.mm b/widget/cocoa/nsMenuBarX.mm index 9762ae22c932..c91ba1f8fbfa 100644 --- a/widget/cocoa/nsMenuBarX.mm +++ b/widget/cocoa/nsMenuBarX.mm @@ -41,10 +41,11 @@ BOOL gSomeMenuBarPainted = NO; // defined in nsCocoaWindow.mm. extern BOOL sTouchBarIsInitialized; -// We keep references to the first quit and pref item content nodes we find, which -// will be from the hidden window. We use these when the document for the current -// window does not have a quit or pref item. We don't need strong refs here because -// these items are always strong ref'd by their owning menu bar (instance variable). +// We keep references to the first quit and pref item content nodes we find, +// which will be from the hidden window. We use these when the document for the +// current window does not have a quit or pref item. We don't need strong refs +// here because these items are always strong ref'd by their owning menu bar +// (instance variable). static nsIContent* sAboutItemContent = nullptr; static nsIContent* sPrefItemContent = nullptr; static nsIContent* sAccountItemContent = nullptr; @@ -140,8 +141,9 @@ void nsMenuBarX::ConstructNativeMenus() { for (nsIContent* menuContent = mContent->GetFirstChild(); menuContent; menuContent = menuContent->GetNextSibling()) { if (menuContent->IsXULElement(nsGkAtoms::menu)) { - InsertMenuAtIndex(MakeRefPtr(this, mMenuGroupOwner, menuContent->AsElement()), - GetMenuCount()); + InsertMenuAtIndex( + MakeRefPtr(this, mMenuGroupOwner, menuContent->AsElement()), + GetMenuCount()); } } } @@ -156,7 +158,8 @@ void nsMenuBarX::ConstructFallbackNativeMenus() { nsCOMPtr stringBundle; - nsCOMPtr bundleSvc = do_GetService(NS_STRINGBUNDLE_CONTRACTID); + nsCOMPtr bundleSvc = + do_GetService(NS_STRINGBUNDLE_CONTRACTID); bundleSvc->CreateBundle("chrome://global/locale/fallbackMenubar.properties", getter_AddRefs(stringBundle)); @@ -173,8 +176,10 @@ void nsMenuBarX::ConstructFallbackNativeMenus() { stringBundle->GetStringFromName(labelProp, labelUTF16); stringBundle->GetStringFromName(keyProp, keyUTF16); - NSString* labelStr = [NSString stringWithUTF8String:NS_ConvertUTF16toUTF8(labelUTF16).get()]; - NSString* keyStr = [NSString stringWithUTF8String:NS_ConvertUTF16toUTF8(keyUTF16).get()]; + NSString* labelStr = + [NSString stringWithUTF8String:NS_ConvertUTF16toUTF8(labelUTF16).get()]; + NSString* keyStr = + [NSString stringWithUTF8String:NS_ConvertUTF16toUTF8(keyUTF16).get()]; if (!nsMenuBarX::sNativeEventTarget) { nsMenuBarX::sNativeEventTarget = [[NativeMenuItemTarget alloc] init]; @@ -182,12 +187,14 @@ void nsMenuBarX::ConstructFallbackNativeMenus() { sApplicationMenu = [[[[NSApp mainMenu] itemAtIndex:0] submenu] retain]; if (!mApplicationMenuDelegate) { - mApplicationMenuDelegate = [[ApplicationMenuDelegate alloc] initWithApplicationMenu:this]; + mApplicationMenuDelegate = + [[ApplicationMenuDelegate alloc] initWithApplicationMenu:this]; } sApplicationMenu.delegate = mApplicationMenuDelegate; - NSMenuItem* quitMenuItem = [[[NSMenuItem alloc] initWithTitle:labelStr - action:@selector(menuItemHit:) - keyEquivalent:keyStr] autorelease]; + NSMenuItem* quitMenuItem = + [[[NSMenuItem alloc] initWithTitle:labelStr + action:@selector(menuItemHit:) + keyEquivalent:keyStr] autorelease]; quitMenuItem.target = nsMenuBarX::sNativeEventTarget; quitMenuItem.tag = eCommand_ID_Quit; [sApplicationMenu addItem:quitMenuItem]; @@ -201,7 +208,8 @@ uint32_t nsMenuBarX::GetMenuCount() { return mMenuArray.Length(); } bool nsMenuBarX::MenuContainsAppMenu() { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; - return (mNativeMenu.numberOfItems > 0 && [mNativeMenu itemAtIndex:0].submenu == sApplicationMenu); + return (mNativeMenu.numberOfItems > 0 && + [mNativeMenu itemAtIndex:0].submenu == sApplicationMenu); NS_OBJC_END_TRY_ABORT_BLOCK; } @@ -220,8 +228,9 @@ void nsMenuBarX::InsertMenuAtIndex(RefPtr&& aMenu, uint32_t aIndex) { // Hook the new Application menu up to the menu bar. NSMenu* mainMenu = NSApp.mainMenu; - NS_ASSERTION(mainMenu.numberOfItems > 0, - "Main menu does not have any items, something is terribly wrong!"); + NS_ASSERTION( + mainMenu.numberOfItems > 0, + "Main menu does not have any items, something is terribly wrong!"); [mainMenu itemAtIndex:0].submenu = sApplicationMenu; } @@ -230,7 +239,8 @@ void nsMenuBarX::InsertMenuAtIndex(RefPtr&& aMenu, uint32_t aIndex) { // hook up submenus RefPtr menuContent = aMenu->Content(); - if (menuContent->GetChildCount() > 0 && !nsMenuUtilsX::NodeIsHiddenOrCollapsed(menuContent)) { + if (menuContent->GetChildCount() > 0 && + !nsMenuUtilsX::NodeIsHiddenOrCollapsed(menuContent)) { MenuChildChangedVisibility(MenuChild(aMenu), true); } @@ -263,11 +273,14 @@ void nsMenuBarX::RemoveMenuAtIndex(uint32_t aIndex) { NS_OBJC_END_TRY_ABORT_BLOCK; } -void nsMenuBarX::ObserveAttributeChanged(mozilla::dom::Document* aDocument, nsIContent* aContent, +void nsMenuBarX::ObserveAttributeChanged(mozilla::dom::Document* aDocument, + nsIContent* aContent, nsAtom* aAttribute) {} -void nsMenuBarX::ObserveContentRemoved(mozilla::dom::Document* aDocument, nsIContent* aContainer, - nsIContent* aChild, nsIContent* aPreviousSibling) { +void nsMenuBarX::ObserveContentRemoved(mozilla::dom::Document* aDocument, + nsIContent* aContainer, + nsIContent* aChild, + nsIContent* aPreviousSibling) { nsINode* parent = NODE_FROM(aContainer, aDocument); MOZ_ASSERT(parent); const Maybe index = parent->ComputeIndexOf(aPreviousSibling); @@ -275,7 +288,8 @@ void nsMenuBarX::ObserveContentRemoved(mozilla::dom::Document* aDocument, nsICon RemoveMenuAtIndex(index.isSome() ? *index + 1u : 0u); } -void nsMenuBarX::ObserveContentInserted(mozilla::dom::Document* aDocument, nsIContent* aContainer, +void nsMenuBarX::ObserveContentInserted(mozilla::dom::Document* aDocument, + nsIContent* aContainer, nsIContent* aChild) { InsertMenuAtIndex(MakeRefPtr(this, mMenuGroupOwner, aChild), aContainer->ComputeIndexOf(aChild).valueOr(UINT32_MAX)); @@ -285,7 +299,8 @@ void nsMenuBarX::ForceUpdateNativeMenuAt(const nsAString& aIndexString) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; NSString* locationString = - [NSString stringWithCharacters:reinterpret_cast(aIndexString.BeginReading()) + [NSString stringWithCharacters:reinterpret_cast( + aIndexString.BeginReading()) length:aIndexString.Length()]; NSArray* indexes = [locationString componentsSeparatedByString:@"|"]; unsigned int indexCount = indexes.count; @@ -329,7 +344,9 @@ void nsMenuBarX::ForceUpdateNativeMenuAt(const nsAString& aIndexString) { } RefPtr content = targetMenu->match( [](const RefPtr& aMenu) { return aMenu->Content(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->Content(); }); + [](const RefPtr& aMenuItem) { + return aMenuItem->Content(); + }); if (!nsMenuUtilsX::NodeIsHiddenOrCollapsed(content)) { visible++; if (targetMenu->is>() && visible == (targetIndex + 1)) { @@ -408,8 +425,9 @@ nsresult nsMenuBarX::Paint() { // We have to keep the same menu item for the Application menu so we keep // passing it along. NSMenu* outgoingMenu = NSApp.mainMenu; - NS_ASSERTION(outgoingMenu.numberOfItems > 0, - "Main menu does not have any items, something is terribly wrong!"); + NS_ASSERTION( + outgoingMenu.numberOfItems > 0, + "Main menu does not have any items, something is terribly wrong!"); NSMenuItem* appMenuItem = [[outgoingMenu itemAtIndex:0] retain]; [outgoingMenu removeItemAtIndex:0]; @@ -456,8 +474,10 @@ bool nsMenuBarX::PerformKeyEquivalent(NSEvent* aEvent) { return [mNativeMenu performSuperKeyEquivalent:aEvent]; } -void nsMenuBarX::MenuChildChangedVisibility(const MenuChild& aChild, bool aIsVisible) { - MOZ_RELEASE_ASSERT(aChild.is>(), "nsMenuBarX only has nsMenuX children"); +void nsMenuBarX::MenuChildChangedVisibility(const MenuChild& aChild, + bool aIsVisible) { + MOZ_RELEASE_ASSERT(aChild.is>(), + "nsMenuBarX only has nsMenuX children"); const RefPtr& child = aChild.as>(); NSMenuItem* item = child->NativeNSMenuItem(); if (aIsVisible) { @@ -475,8 +495,9 @@ NSInteger nsMenuBarX::CalculateNativeInsertionPoint(nsMenuX* aChild) { return insertionPoint; } // Only count items that are inside a menu. - // XXXmstange Not sure what would cause free-standing items. Maybe for collapsed/hidden menus? - // In that case, an nsMenuX::IsVisible() method would be better. + // XXXmstange Not sure what would cause free-standing items. Maybe for + // collapsed/hidden menus? In that case, an nsMenuX::IsVisible() method + // would be better. if (currMenu->NativeNSMenuItem().menu) { insertionPoint++; } @@ -486,10 +507,12 @@ NSInteger nsMenuBarX::CalculateNativeInsertionPoint(nsMenuX* aChild) { // Hide the item in the menu by setting the 'hidden' attribute. Returns it so // the caller can hang onto it if they so choose. -RefPtr nsMenuBarX::HideItem(mozilla::dom::Document* aDocument, const nsAString& aID) { +RefPtr nsMenuBarX::HideItem(mozilla::dom::Document* aDocument, + const nsAString& aID) { RefPtr menuElement = aDocument->GetElementById(aID); if (menuElement) { - menuElement->SetAttr(kNameSpaceID_None, nsGkAtoms::hidden, u"true"_ns, false); + menuElement->SetAttr(kNameSpaceID_None, nsGkAtoms::hidden, u"true"_ns, + false); } return menuElement; } @@ -536,7 +559,8 @@ void nsMenuBarX::AquifyMenuBar() { } // for creating menu items destined for the Application menu -NSMenuItem* nsMenuBarX::CreateNativeAppMenuItem(nsMenuX* aMenu, const nsAString& aNodeID, +NSMenuItem* nsMenuBarX::CreateNativeAppMenuItem(nsMenuX* aMenu, + const nsAString& aNodeID, SEL aAction, int aTag, NativeMenuItemTarget* aTarget) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; @@ -553,8 +577,8 @@ NSMenuItem* nsMenuBarX::CreateNativeAppMenuItem(nsMenuX* aMenu, const nsAString& // Check collapsed rather than hidden since the app menu items are always // hidden in AquifyMenuBar. - if (menuItem->AttrValueIs(kNameSpaceID_None, nsGkAtoms::collapsed, nsGkAtoms::_true, - eCaseMatters)) { + if (menuItem->AttrValueIs(kNameSpaceID_None, nsGkAtoms::collapsed, + nsGkAtoms::_true, eCaseMatters)) { return nil; } @@ -577,20 +601,23 @@ NSMenuItem* nsMenuBarX::CreateNativeAppMenuItem(nsMenuX* aMenu, const nsAString& nsAutoString keyChar(u" "_ns); keyElement->GetAttr(nsGkAtoms::key, keyChar); if (!keyChar.EqualsLiteral(" ")) { - keyEquiv = [[NSString stringWithCharacters:reinterpret_cast(keyChar.get()) - length:keyChar.Length()] lowercaseString]; + keyEquiv = [[NSString + stringWithCharacters:reinterpret_cast(keyChar.get()) + length:keyChar.Length()] lowercaseString]; } // now grab the key equivalent modifiers nsAutoString modifiersStr; keyElement->GetAttr(nsGkAtoms::modifiers, modifiersStr); - uint8_t geckoModifiers = nsMenuUtilsX::GeckoModifiersForNodeAttribute(modifiersStr); - macKeyModifiers = nsMenuUtilsX::MacModifiersForGeckoModifiers(geckoModifiers); + uint8_t geckoModifiers = + nsMenuUtilsX::GeckoModifiersForNodeAttribute(modifiersStr); + macKeyModifiers = + nsMenuUtilsX::MacModifiersForGeckoModifiers(geckoModifiers); } } // get the label into NSString-form - NSString* labelString = - [NSString stringWithCharacters:reinterpret_cast(label.get()) - length:label.Length()]; + NSString* labelString = [NSString + stringWithCharacters:reinterpret_cast(label.get()) + length:label.Length()]; if (!labelString) { labelString = @""; @@ -634,7 +661,8 @@ void nsMenuBarX::CreateApplicationMenu(nsMenuX* aMenu) { = Preferences... = <- menu_preferences = Account Settings = <- menu_accountmgr Only on Thunderbird ======================== - = Services > = <- menu_mac_services <- (do not define key equivalent) + = Services > = <- menu_mac_services <- (do not define key + equivalent) ======================== = Hide App = <- menu_mac_hide_app = Hide Others = <- menu_mac_hide_others @@ -646,34 +674,37 @@ void nsMenuBarX::CreateApplicationMenu(nsMenuX* aMenu) { ======================== If any of them are ommitted from the application's DOM, we just don't add - them. We always add a "Quit" item, but if an app developer does not provide a - DOM node with the right ID for the Quit item, we add it in English. App - developers need only add each node with a label and a key equivalent (if they - want one). Other attributes are optional. Like so: + them. We always add a "Quit" item, but if an app developer does not provide + a DOM node with the right ID for the Quit item, we add it in English. App + developers need only add each node with a label and a key equivalent (if + they want one). Other attributes are optional. Like so: - We need to use this system for localization purposes, until we have a better way - to define the Application menu to be used on Mac OS X. + We need to use this system for localization purposes, until we have a better + way to define the Application menu to be used on Mac OS X. */ if (sApplicationMenu) { if (!mApplicationMenuDelegate) { - mApplicationMenuDelegate = [[ApplicationMenuDelegate alloc] initWithApplicationMenu:this]; + mApplicationMenuDelegate = + [[ApplicationMenuDelegate alloc] initWithApplicationMenu:this]; } sApplicationMenu.delegate = mApplicationMenuDelegate; - // This code reads attributes we are going to care about from the DOM elements + // This code reads attributes we are going to care about from the DOM + // elements NSMenuItem* itemBeingAdded = nil; BOOL addAboutSeparator = FALSE; BOOL addPrefsSeparator = FALSE; // Add the About menu item - itemBeingAdded = CreateNativeAppMenuItem(aMenu, u"aboutName"_ns, @selector(menuItemHit:), - eCommand_ID_About, nsMenuBarX::sNativeEventTarget); + itemBeingAdded = CreateNativeAppMenuItem( + aMenu, u"aboutName"_ns, @selector(menuItemHit:), eCommand_ID_About, + nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -688,8 +719,9 @@ void nsMenuBarX::CreateApplicationMenu(nsMenuX* aMenu) { } // Add the Preferences menu item - itemBeingAdded = CreateNativeAppMenuItem(aMenu, u"menu_preferences"_ns, @selector(menuItemHit:), - eCommand_ID_Prefs, nsMenuBarX::sNativeEventTarget); + itemBeingAdded = CreateNativeAppMenuItem( + aMenu, u"menu_preferences"_ns, @selector(menuItemHit:), + eCommand_ID_Prefs, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -699,8 +731,9 @@ void nsMenuBarX::CreateApplicationMenu(nsMenuX* aMenu) { } // Add the Account Settings menu item. This is Thunderbird only - itemBeingAdded = CreateNativeAppMenuItem(aMenu, u"menu_accountmgr"_ns, @selector(menuItemHit:), - eCommand_ID_Account, nsMenuBarX::sNativeEventTarget); + itemBeingAdded = CreateNativeAppMenuItem( + aMenu, u"menu_accountmgr"_ns, @selector(menuItemHit:), + eCommand_ID_Account, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -713,7 +746,8 @@ void nsMenuBarX::CreateApplicationMenu(nsMenuX* aMenu) { } // Add Services menu item - itemBeingAdded = CreateNativeAppMenuItem(aMenu, u"menu_mac_services"_ns, nil, 0, nil); + itemBeingAdded = + CreateNativeAppMenuItem(aMenu, u"menu_mac_services"_ns, nil, 0, nil); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; @@ -732,9 +766,9 @@ void nsMenuBarX::CreateApplicationMenu(nsMenuX* aMenu) { BOOL addHideShowSeparator = FALSE; // Add menu item to hide this application - itemBeingAdded = - CreateNativeAppMenuItem(aMenu, u"menu_mac_hide_app"_ns, @selector(menuItemHit:), - eCommand_ID_HideApp, nsMenuBarX::sNativeEventTarget); + itemBeingAdded = CreateNativeAppMenuItem( + aMenu, u"menu_mac_hide_app"_ns, @selector(menuItemHit:), + eCommand_ID_HideApp, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -744,9 +778,9 @@ void nsMenuBarX::CreateApplicationMenu(nsMenuX* aMenu) { } // Add menu item to hide other applications - itemBeingAdded = - CreateNativeAppMenuItem(aMenu, u"menu_mac_hide_others"_ns, @selector(menuItemHit:), - eCommand_ID_HideOthers, nsMenuBarX::sNativeEventTarget); + itemBeingAdded = CreateNativeAppMenuItem( + aMenu, u"menu_mac_hide_others"_ns, @selector(menuItemHit:), + eCommand_ID_HideOthers, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -756,9 +790,9 @@ void nsMenuBarX::CreateApplicationMenu(nsMenuX* aMenu) { } // Add menu item to show all applications - itemBeingAdded = - CreateNativeAppMenuItem(aMenu, u"menu_mac_show_all"_ns, @selector(menuItemHit:), - eCommand_ID_ShowAll, nsMenuBarX::sNativeEventTarget); + itemBeingAdded = CreateNativeAppMenuItem( + aMenu, u"menu_mac_show_all"_ns, @selector(menuItemHit:), + eCommand_ID_ShowAll, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -775,9 +809,9 @@ void nsMenuBarX::CreateApplicationMenu(nsMenuX* aMenu) { BOOL addTouchBarSeparator = NO; // Add Touch Bar customization menu item. - itemBeingAdded = - CreateNativeAppMenuItem(aMenu, u"menu_mac_touch_bar"_ns, @selector(menuItemHit:), - eCommand_ID_TouchBar, nsMenuBarX::sNativeEventTarget); + itemBeingAdded = CreateNativeAppMenuItem( + aMenu, u"menu_mac_touch_bar"_ns, @selector(menuItemHit:), + eCommand_ID_TouchBar, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; @@ -797,9 +831,9 @@ void nsMenuBarX::CreateApplicationMenu(nsMenuX* aMenu) { } // Add quit menu item - itemBeingAdded = - CreateNativeAppMenuItem(aMenu, u"menu_FileQuitItem"_ns, @selector(menuItemHit:), - eCommand_ID_Quit, nsMenuBarX::sNativeEventTarget); + itemBeingAdded = CreateNativeAppMenuItem( + aMenu, u"menu_FileQuitItem"_ns, @selector(menuItemHit:), + eCommand_ID_Quit, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -807,9 +841,10 @@ void nsMenuBarX::CreateApplicationMenu(nsMenuX* aMenu) { } else { // the current application does not have a DOM node for "Quit". Add one // anyway, in English. - NSMenuItem* defaultQuitItem = [[[NSMenuItem alloc] initWithTitle:@"Quit" - action:@selector(menuItemHit:) - keyEquivalent:@"q"] autorelease]; + NSMenuItem* defaultQuitItem = + [[[NSMenuItem alloc] initWithTitle:@"Quit" + action:@selector(menuItemHit:) + keyEquivalent:@"q"] autorelease]; defaultQuitItem.target = nsMenuBarX::sNativeEventTarget; defaultQuitItem.tag = eCommand_ID_Quit; [sApplicationMenu addItem:defaultQuitItem]; @@ -860,9 +895,9 @@ static BOOL gMenuItemsExecuteCommands = YES; [super performKeyEquivalent:aEvent]; gMenuItemsExecuteCommands = YES; // return to default - // Return YES if we invoked a command and there is now no key window or we changed - // the first responder. In this case we do not want to propagate the event because - // we don't want it handled again. + // Return YES if we invoked a command and there is now no key window or we + // changed the first responder. In this case we do not want to propagate the + // event because we don't want it handled again. if (!NSApp.keyWindow || NSApp.keyWindow.firstResponder != firstResponder) { return YES; } @@ -898,7 +933,8 @@ static BOOL gMenuItemsExecuteCommands = YES; nsMenuGroupOwnerX* menuGroupOwner = nullptr; nsMenuBarX* menuBar = nullptr; - MOZMenuItemRepresentedObject* representedObject = nativeMenuItem.representedObject; + MOZMenuItemRepresentedObject* representedObject = + nativeMenuItem.representedObject; if (representedObject) { menuGroupOwner = representedObject.menuGroupOwner; @@ -914,13 +950,15 @@ static BOOL gMenuItemsExecuteCommands = YES; [(MenuDelegate*)menu.delegate menu:menu willActivateItem:nativeMenuItem]; } - // Get the modifier flags and button for this menu item activation. The menu system does not pass - // an NSEvent to our action selector, but we can query the current NSEvent instead. The current - // NSEvent can be a key event or a mouseup event, depending on how the menu item is activated. - NSEventModifierFlags modifierFlags = NSApp.currentEvent ? NSApp.currentEvent.modifierFlags : 0; - mozilla::MouseButton button = NSApp.currentEvent - ? nsCocoaUtils::ButtonForEvent(NSApp.currentEvent) - : mozilla::MouseButton::ePrimary; + // Get the modifier flags and button for this menu item activation. The menu + // system does not pass an NSEvent to our action selector, but we can query + // the current NSEvent instead. The current NSEvent can be a key event or a + // mouseup event, depending on how the menu item is activated. + NSEventModifierFlags modifierFlags = + NSApp.currentEvent ? NSApp.currentEvent.modifierFlags : 0; + mozilla::MouseButton button = + NSApp.currentEvent ? nsCocoaUtils::ButtonForEvent(NSApp.currentEvent) + : mozilla::MouseButton::ePrimary; // Do special processing if this is for an app-global command. if (tag == eCommand_ID_About) { @@ -968,13 +1006,15 @@ static BOOL gMenuItemsExecuteCommands = YES; if (menuBar && menuBar->mQuitItemContent) { mostSpecificContent = menuBar->mQuitItemContent; } - // If we have some content for quit we execute it. Otherwise we send a native app terminate - // message. If you want to stop a quit from happening, provide quit content and return - // the event as unhandled. + // If we have some content for quit we execute it. Otherwise we send a + // native app terminate message. If you want to stop a quit from happening, + // provide quit content and return the event as unhandled. if (mostSpecificContent) { - nsMenuUtilsX::DispatchCommandTo(mostSpecificContent, modifierFlags, button); + nsMenuUtilsX::DispatchCommandTo(mostSpecificContent, modifierFlags, + button); } else { - nsCOMPtr appStartup = mozilla::components::AppStartup::Service(); + nsCOMPtr appStartup = + mozilla::components::AppStartup::Service(); if (appStartup) { bool userAllowedQuit = true; appStartup->Quit(nsIAppStartup::eAttemptQuit, 0, &userAllowedQuit); @@ -986,12 +1026,13 @@ static BOOL gMenuItemsExecuteCommands = YES; // given the commandID, look it up in our hashtable and dispatch to // that menu item. if (menuGroupOwner) { - if (RefPtr menuItem = - menuGroupOwner->GetMenuItemForCommandID(static_cast(tag))) { + if (RefPtr menuItem = menuGroupOwner->GetMenuItemForCommandID( + static_cast(tag))) { if (nsMenuUtilsX::gIsSynchronouslyActivatingNativeMenuItemDuringTest) { menuItem->DoCommand(modifierFlags, button); } else if (RefPtr menu = menuItem->ParentMenu()) { - menu->ActivateItemAfterClosing(std::move(menuItem), modifierFlags, button); + menu->ActivateItemAfterClosing(std::move(menuItem), modifierFlags, + button); } } } @@ -1041,7 +1082,9 @@ static BOOL gMenuItemsExecuteCommands = YES; - (NSMenuItem*)addItemWithTitle:(NSString*)aString action:(SEL)aSelector keyEquivalent:(NSString*)aKeyEquiv { - NSMenuItem* newItem = [super addItemWithTitle:aString action:aSelector keyEquivalent:aKeyEquiv]; + NSMenuItem* newItem = [super addItemWithTitle:aString + action:aSelector + keyEquivalent:aKeyEquiv]; [self _overrideClassOfMenuItem:newItem]; return newItem; } diff --git a/widget/cocoa/nsMenuGroupOwnerX.mm b/widget/cocoa/nsMenuGroupOwnerX.mm index e7a0d2cf8774..45d074e12f92 100644 --- a/widget/cocoa/nsMenuGroupOwnerX.mm +++ b/widget/cocoa/nsMenuGroupOwnerX.mm @@ -26,13 +26,16 @@ using namespace mozilla; NS_IMPL_ISUPPORTS(nsMenuGroupOwnerX, nsIObserver, nsIMutationObserver) -nsMenuGroupOwnerX::nsMenuGroupOwnerX(mozilla::dom::Element* aElement, nsMenuBarX* aMenuBarIfMenuBar) +nsMenuGroupOwnerX::nsMenuGroupOwnerX(mozilla::dom::Element* aElement, + nsMenuBarX* aMenuBarIfMenuBar) : mContent(aElement), mMenuBar(aMenuBarIfMenuBar) { - mRepresentedObject = [[MOZMenuItemRepresentedObject alloc] initWithMenuGroupOwner:this]; + mRepresentedObject = + [[MOZMenuItemRepresentedObject alloc] initWithMenuGroupOwner:this]; } nsMenuGroupOwnerX::~nsMenuGroupOwnerX() { - MOZ_ASSERT(mContentToObserverTable.Count() == 0, "have outstanding mutation observers!\n"); + MOZ_ASSERT(mContentToObserverTable.Count() == 0, + "have outstanding mutation observers!\n"); [mRepresentedObject setMenuGroupOwner:nullptr]; [mRepresentedObject release]; } @@ -41,11 +44,11 @@ nsMenuGroupOwnerX::~nsMenuGroupOwnerX() { // nsIMutationObserver // -void nsMenuGroupOwnerX::CharacterDataWillChange(nsIContent* aContent, - const CharacterDataChangeInfo&) {} +void nsMenuGroupOwnerX::CharacterDataWillChange( + nsIContent* aContent, const CharacterDataChangeInfo&) {} -void nsMenuGroupOwnerX::CharacterDataChanged(nsIContent* aContent, const CharacterDataChangeInfo&) { -} +void nsMenuGroupOwnerX::CharacterDataChanged(nsIContent* aContent, + const CharacterDataChangeInfo&) {} void nsMenuGroupOwnerX::ContentAppended(nsIContent* aFirstNewContent) { for (nsIContent* cur = aFirstNewContent; cur; cur = cur->GetNextSibling()) { @@ -55,10 +58,13 @@ void nsMenuGroupOwnerX::ContentAppended(nsIContent* aFirstNewContent) { void nsMenuGroupOwnerX::NodeWillBeDestroyed(nsINode* aNode) {} -void nsMenuGroupOwnerX::AttributeWillChange(dom::Element* aElement, int32_t aNameSpaceID, - nsAtom* aAttribute, int32_t aModType) {} +void nsMenuGroupOwnerX::AttributeWillChange(dom::Element* aElement, + int32_t aNameSpaceID, + nsAtom* aAttribute, + int32_t aModType) {} -void nsMenuGroupOwnerX::AttributeChanged(dom::Element* aElement, int32_t aNameSpaceID, +void nsMenuGroupOwnerX::AttributeChanged(dom::Element* aElement, + int32_t aNameSpaceID, nsAtom* aAttribute, int32_t aModType, const nsAttrValue* aOldValue) { nsCOMPtr kungFuDeathGrip(this); @@ -68,7 +74,8 @@ void nsMenuGroupOwnerX::AttributeChanged(dom::Element* aElement, int32_t aNameSp } } -void nsMenuGroupOwnerX::ContentRemoved(nsIContent* aChild, nsIContent* aPreviousSibling) { +void nsMenuGroupOwnerX::ContentRemoved(nsIContent* aChild, + nsIContent* aPreviousSibling) { nsIContent* container = aChild->GetParent(); if (!container) { return; @@ -77,7 +84,8 @@ void nsMenuGroupOwnerX::ContentRemoved(nsIContent* aChild, nsIContent* aPrevious nsCOMPtr kungFuDeathGrip(this); nsChangeObserver* obs = LookupContentChangeObserver(container); if (obs) { - obs->ObserveContentRemoved(aChild->OwnerDoc(), container, aChild, aPreviousSibling); + obs->ObserveContentRemoved(aChild->OwnerDoc(), container, aChild, + aPreviousSibling); } else if (container != mContent) { // We do a lookup on the parent container in case things were removed // under a "menupopup" item. That is basically a wrapper for the contents @@ -86,7 +94,8 @@ void nsMenuGroupOwnerX::ContentRemoved(nsIContent* aChild, nsIContent* aPrevious if (parent) { obs = LookupContentChangeObserver(parent); if (obs) { - obs->ObserveContentRemoved(aChild->OwnerDoc(), container, aChild, aPreviousSibling); + obs->ObserveContentRemoved(aChild->OwnerDoc(), container, aChild, + aPreviousSibling); } } } @@ -118,18 +127,18 @@ void nsMenuGroupOwnerX::ContentInserted(nsIContent* aChild) { void nsMenuGroupOwnerX::ParentChainChanged(nsIContent* aContent) {} -void nsMenuGroupOwnerX::ARIAAttributeDefaultWillChange(mozilla::dom::Element* aElement, - nsAtom* aAttribute, int32_t aModType) {} +void nsMenuGroupOwnerX::ARIAAttributeDefaultWillChange( + mozilla::dom::Element* aElement, nsAtom* aAttribute, int32_t aModType) {} -void nsMenuGroupOwnerX::ARIAAttributeDefaultChanged(mozilla::dom::Element* aElement, - nsAtom* aAttribute, int32_t aModType) {} +void nsMenuGroupOwnerX::ARIAAttributeDefaultChanged( + mozilla::dom::Element* aElement, nsAtom* aAttribute, int32_t aModType) {} // For change management, we don't use a |nsSupportsHashtable| because // we know that the lifetime of all these items is bounded by the // lifetime of the menubar. No need to add any more strong refs to the // picture because the containment hierarchy already uses strong refs. -void nsMenuGroupOwnerX::RegisterForContentChanges(nsIContent* aContent, - nsChangeObserver* aMenuObject) { +void nsMenuGroupOwnerX::RegisterForContentChanges( + nsIContent* aContent, nsChangeObserver* aMenuObject) { if (!mContentToObserverTable.Contains(aContent)) { aContent->AddMutationObserver(this); } @@ -158,7 +167,8 @@ void nsMenuGroupOwnerX::UnregisterForLocaleChanges() { } NS_IMETHODIMP -nsMenuGroupOwnerX::Observe(nsISupports* aSubject, const char* aTopic, const char16_t* aData) { +nsMenuGroupOwnerX::Observe(nsISupports* aSubject, const char* aTopic, + const char16_t* aData) { if (mMenuBar && !strcmp(aTopic, "intl:app-locales-changed")) { // Rebuild the menu with the new locale strings. mMenuBar->SetNeedsRebuild(); @@ -166,7 +176,8 @@ nsMenuGroupOwnerX::Observe(nsISupports* aSubject, const char* aTopic, const char return NS_OK; } -nsChangeObserver* nsMenuGroupOwnerX::LookupContentChangeObserver(nsIContent* aContent) { +nsChangeObserver* nsMenuGroupOwnerX::LookupContentChangeObserver( + nsIContent* aContent) { nsChangeObserver* result; if (mContentToObserverTable.Get(aContent, &result)) { return result; @@ -206,7 +217,8 @@ nsMenuItemX* nsMenuGroupOwnerX::GetMenuItemForCommandID(uint32_t aCommandID) { } @implementation MOZMenuItemRepresentedObject { - nsMenuGroupOwnerX* mMenuGroupOwner; // weak, cleared by nsMenuGroupOwnerX's destructor + nsMenuGroupOwnerX* + mMenuGroupOwner; // weak, cleared by nsMenuGroupOwnerX's destructor } - (id)initWithMenuGroupOwner:(nsMenuGroupOwnerX*)aMenuGroupOwner { diff --git a/widget/cocoa/nsMenuItemIconX.mm b/widget/cocoa/nsMenuItemIconX.mm index d00e8eb039a3..6749d787de09 100644 --- a/widget/cocoa/nsMenuItemIconX.mm +++ b/widget/cocoa/nsMenuItemIconX.mm @@ -62,8 +62,8 @@ void nsMenuItemIconX::SetupIcon(nsIContent* aContent) { bool shouldHaveIcon = StartIconLoad(aContent); if (!shouldHaveIcon) { - // There is no icon for this menu item, as an error occurred while loading it. - // An icon might have been set earlier or the place holder icon may have + // There is no icon for this menu item, as an error occurred while loading + // it. An icon might have been set earlier or the place holder icon may have // been set. Clear it. if (mIconImage) { [mIconImage release]; @@ -73,8 +73,9 @@ void nsMenuItemIconX::SetupIcon(nsIContent* aContent) { } if (!mIconImage) { - // Set a placeholder icon, so that the menuitem reserves space for the icon during the load and - // there is no sudden shift once the icon finishes loading. + // Set a placeholder icon, so that the menuitem reserves space for the icon + // during the load and there is no sudden shift once the icon finishes + // loading. NSSize iconSize = NSMakeSize(kIconSize, kIconSize); mIconImage = [[MOZIconHelper placeholderIconWithSize:iconSize] retain]; } @@ -100,7 +101,8 @@ already_AddRefed nsMenuItemIconX::GetIconURI(nsIContent* aContent) { // First, look at the content node's "image" attribute. nsAutoString imageURIString; bool hasImageAttr = - aContent->IsElement() && aContent->AsElement()->GetAttr(nsGkAtoms::image, imageURIString); + aContent->IsElement() && + aContent->AsElement()->GetAttr(nsGkAtoms::image, imageURIString); if (hasImageAttr) { // Use the URL from the image attribute. @@ -121,7 +123,8 @@ already_AddRefed nsMenuItemIconX::GetIconURI(nsIContent* aContent) { return nullptr; } - RefPtr sc = nsComputedDOMStyle::GetComputedStyle(aContent->AsElement()); + RefPtr sc = + nsComputedDOMStyle::GetComputedStyle(aContent->AsElement()); if (!sc) { return nullptr; } @@ -149,11 +152,12 @@ nsresult nsMenuItemIconX::OnComplete(imgIContainer* aImage) { mIconImage = nil; } RefPtr pc = mPresContext.get(); - mIconImage = [[MOZIconHelper iconImageFromImageContainer:aImage - withSize:NSMakeSize(kIconSize, kIconSize) - presContext:pc - computedStyle:mComputedStyle - scaleFactor:0.0f] retain]; + mIconImage = [[MOZIconHelper + iconImageFromImageContainer:aImage + withSize:NSMakeSize(kIconSize, kIconSize) + presContext:pc + computedStyle:mComputedStyle + scaleFactor:0.0f] retain]; mComputedStyle = nullptr; mPresContext = nullptr; diff --git a/widget/cocoa/nsMenuItemX.mm b/widget/cocoa/nsMenuItemX.mm index c085d6b04722..22e7082bb05d 100644 --- a/widget/cocoa/nsMenuItemX.mm +++ b/widget/cocoa/nsMenuItemX.mm @@ -26,14 +26,19 @@ using namespace mozilla; using mozilla::dom::CallerType; using mozilla::dom::Event; -nsMenuItemX::nsMenuItemX(nsMenuX* aParent, const nsString& aLabel, EMenuItemType aItemType, +nsMenuItemX::nsMenuItemX(nsMenuX* aParent, const nsString& aLabel, + EMenuItemType aItemType, nsMenuGroupOwnerX* aMenuGroupOwner, nsIContent* aNode) - : mContent(aNode), mType(aItemType), mMenuParent(aParent), mMenuGroupOwner(aMenuGroupOwner) { + : mContent(aNode), + mType(aItemType), + mMenuParent(aParent), + mMenuGroupOwner(aMenuGroupOwner) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; MOZ_COUNT_CTOR(nsMenuItemX); - MOZ_RELEASE_ASSERT(mContent->IsElement(), "nsMenuItemX should only be created for elements"); + MOZ_RELEASE_ASSERT(mContent->IsElement(), + "nsMenuItemX should only be created for elements"); NS_ASSERTION(mMenuGroupOwner, "No menu owner given, must have one!"); mMenuGroupOwner->RegisterForContentChanges(mContent, this); @@ -57,28 +62,29 @@ nsMenuItemX::nsMenuItemX(nsMenuX* aParent, const nsString& aLabel, EMenuItemType } } - // decide enabled state based on command content if it exists, otherwise do it based - // on our own content + // decide enabled state based on command content if it exists, otherwise do it + // based on our own content bool isEnabled; if (mCommandElement) { - isEnabled = !mCommandElement->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled, - nsGkAtoms::_true, eCaseMatters); + isEnabled = !mCommandElement->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::disabled, nsGkAtoms::_true, eCaseMatters); } else { - isEnabled = !mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled, - nsGkAtoms::_true, eCaseMatters); + isEnabled = !mContent->AsElement()->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::disabled, nsGkAtoms::_true, eCaseMatters); } // set up the native menu item if (mType == eSeparatorMenuItemType) { mNativeMenuItem = [[NSMenuItem separatorItem] retain]; } else { - NSString* newCocoaLabelString = nsMenuUtilsX::GetTruncatedCocoaLabel(aLabel); + NSString* newCocoaLabelString = + nsMenuUtilsX::GetTruncatedCocoaLabel(aLabel); mNativeMenuItem = [[NSMenuItem alloc] initWithTitle:newCocoaLabelString action:nil keyEquivalent:@""]; - mIsChecked = mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::checked, - nsGkAtoms::_true, eCaseMatters); + mIsChecked = mContent->AsElement()->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::checked, nsGkAtoms::_true, eCaseMatters); mNativeMenuItem.enabled = isEnabled; mNativeMenuItem.state = mIsChecked ? NSOnState : NSOffState; @@ -141,9 +147,11 @@ nsresult nsMenuItemX::SetChecked(bool aIsChecked) { // update the content model. This will also handle unchecking our siblings // if we are a radiomenu if (mIsChecked) { - mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::checked, u"true"_ns, true); + mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::checked, + u"true"_ns, true); } else { - mContent->AsElement()->UnsetAttr(kNameSpaceID_None, nsGkAtoms::checked, true); + mContent->AsElement()->UnsetAttr(kNameSpaceID_None, nsGkAtoms::checked, + true); } // update native menu item @@ -158,10 +166,13 @@ EMenuItemType nsMenuItemX::GetMenuItemType() { return mType; } // Executes the "cached" javaScript command. // Returns NS_OK if the command was executed properly, otherwise an error code. -void nsMenuItemX::DoCommand(NSEventModifierFlags aModifierFlags, int16_t aButton) { +void nsMenuItemX::DoCommand(NSEventModifierFlags aModifierFlags, + int16_t aButton) { // flip "checked" state if we're a checkbox menu, or an un-checked radio menu - if (mType == eCheckboxMenuItemType || (mType == eRadioMenuItemType && !mIsChecked)) { - if (!mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::autocheck, + if (mType == eCheckboxMenuItemType || + (mType == eRadioMenuItemType && !mIsChecked)) { + if (!mContent->AsElement()->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::autocheck, nsGkAtoms::_false, eCaseMatters)) { SetChecked(!mIsChecked); } @@ -171,7 +182,8 @@ void nsMenuItemX::DoCommand(NSEventModifierFlags aModifierFlags, int16_t aButton nsMenuUtilsX::DispatchCommandTo(mContent, aModifierFlags, aButton); } -nsresult nsMenuItemX::DispatchDOMEvent(const nsString& eventName, bool* preventDefaultCalled) { +nsresult nsMenuItemX::DispatchDOMEvent(const nsString& eventName, + bool* preventDefaultCalled) { if (!mContent) { return NS_ERROR_FAILURE; } @@ -181,7 +193,8 @@ nsresult nsMenuItemX::DispatchDOMEvent(const nsString& eventName, bool* preventD // create DOM event ErrorResult rv; - RefPtr event = parentDoc->CreateEvent(u"Events"_ns, CallerType::System, rv); + RefPtr event = + parentDoc->CreateEvent(u"Events"_ns, CallerType::System, rv); if (rv.Failed()) { NS_WARNING("Failed to create Event"); return rv.StealNSResult(); @@ -192,7 +205,8 @@ nsresult nsMenuItemX::DispatchDOMEvent(const nsString& eventName, bool* preventD event->SetTrusted(true); // send DOM event - *preventDefaultCalled = mContent->DispatchEvent(*event, CallerType::System, rv); + *preventDefaultCalled = + mContent->DispatchEvent(*event, CallerType::System, rv); if (rv.Failed()) { NS_WARNING("Failed to send DOM event via EventTarget"); return rv.StealNSResult(); @@ -220,9 +234,10 @@ void nsMenuItemX::UncheckRadioSiblings(nsIContent* aCheckedContent) { sibling = sibling->GetNextSibling()) { if (sibling != aCheckedContent && sibling->IsElement()) { // skip this node // if the current sibling is in the same group, clear it - if (sibling->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::name, myGroupName, - eCaseMatters)) { - sibling->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::checked, u"false"_ns, true); + if (sibling->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::name, + myGroupName, eCaseMatters)) { + sibling->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::checked, + u"false"_ns, true); } } } @@ -236,7 +251,8 @@ void nsMenuItemX::SetKeyEquiv() { mContent->AsElement()->GetAttr(nsGkAtoms::key, keyValue); if (!keyValue.IsEmpty() && mContent->GetUncomposedDoc()) { - dom::Element* keyContent = mContent->GetUncomposedDoc()->GetElementById(keyValue); + dom::Element* keyContent = + mContent->GetUncomposedDoc()->GetElementById(keyValue); if (keyContent) { nsAutoString keyChar; bool hasKey = keyContent->GetAttr(nsGkAtoms::key, keyChar); @@ -244,7 +260,8 @@ void nsMenuItemX::SetKeyEquiv() { if (!hasKey || keyChar.IsEmpty()) { nsAutoString keyCodeName; keyContent->GetAttr(nsGkAtoms::keycode, keyCodeName); - uint32_t charCode = nsCocoaUtils::ConvertGeckoNameToMacCharCode(keyCodeName); + uint32_t charCode = + nsCocoaUtils::ConvertGeckoNameToMacCharCode(keyCodeName); if (charCode) { keyChar.Assign(charCode); } else { @@ -254,13 +271,16 @@ void nsMenuItemX::SetKeyEquiv() { nsAutoString modifiersStr; keyContent->GetAttr(nsGkAtoms::modifiers, modifiersStr); - uint8_t modifiers = nsMenuUtilsX::GeckoModifiersForNodeAttribute(modifiersStr); + uint8_t modifiers = + nsMenuUtilsX::GeckoModifiersForNodeAttribute(modifiersStr); - unsigned int macModifiers = nsMenuUtilsX::MacModifiersForGeckoModifiers(modifiers); + unsigned int macModifiers = + nsMenuUtilsX::MacModifiersForGeckoModifiers(modifiers); mNativeMenuItem.keyEquivalentModifierMask = macModifiers; - NSString* keyEquivalent = [[NSString stringWithCharacters:(unichar*)keyChar.get() - length:keyChar.Length()] lowercaseString]; + NSString* keyEquivalent = + [[NSString stringWithCharacters:(unichar*)keyChar.get() + length:keyChar.Length()] lowercaseString]; if ([keyEquivalent isEqualToString:@" "]) { mNativeMenuItem.keyEquivalent = @""; } else { @@ -279,7 +299,8 @@ void nsMenuItemX::SetKeyEquiv() { void nsMenuItemX::Dump(uint32_t aIndent) const { printf("%*s - item [%p] %-16s <%s>\n", aIndent * 2, "", this, - mType == eSeparatorMenuItemType ? "----" : [mNativeMenuItem.title UTF8String], + mType == eSeparatorMenuItemType ? "----" + : [mNativeMenuItem.title UTF8String], NS_ConvertUTF16toUTF8(mContent->NodeName()).get()); } @@ -287,7 +308,8 @@ void nsMenuItemX::Dump(uint32_t aIndent) const { // nsChangeObserver // -void nsMenuItemX::ObserveAttributeChanged(dom::Document* aDocument, nsIContent* aContent, +void nsMenuItemX::ObserveAttributeChanged(dom::Document* aDocument, + nsIContent* aContent, nsAtom* aAttribute) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; @@ -300,17 +322,20 @@ void nsMenuItemX::ObserveAttributeChanged(dom::Document* aDocument, nsIContent* // if we're a radio menu, uncheck our sibling radio items. No need to // do any of this if we're just a normal check menu. if (mType == eRadioMenuItemType && - mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::checked, + mContent->AsElement()->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::checked, nsGkAtoms::_true, eCaseMatters)) { UncheckRadioSiblings(mContent); } mMenuParent->SetRebuild(true); - } else if (aAttribute == nsGkAtoms::hidden || aAttribute == nsGkAtoms::collapsed) { + } else if (aAttribute == nsGkAtoms::hidden || + aAttribute == nsGkAtoms::collapsed) { bool isVisible = !nsMenuUtilsX::NodeIsHiddenOrCollapsed(mContent); if (isVisible != mIsVisible) { mIsVisible = isVisible; RefPtr self = this; - mMenuParent->MenuChildChangedVisibility(nsMenuParentX::MenuChild(self), isVisible); + mMenuParent->MenuChildChangedVisibility(nsMenuParentX::MenuChild(self), + isVisible); if (mIsVisible) { SetupIcon(); } @@ -328,7 +353,8 @@ void nsMenuItemX::ObserveAttributeChanged(dom::Document* aDocument, nsIContent* SetupIcon(); } else if (aAttribute == nsGkAtoms::disabled) { mNativeMenuItem.enabled = !aContent->AsElement()->AttrValueIs( - kNameSpaceID_None, nsGkAtoms::disabled, nsGkAtoms::_true, eCaseMatters); + kNameSpaceID_None, nsGkAtoms::disabled, nsGkAtoms::_true, + eCaseMatters); } } else if (aContent == mCommandElement) { // the only thing that really matters when the menu isn't showing is the @@ -342,15 +368,17 @@ void nsMenuItemX::ObserveAttributeChanged(dom::Document* aDocument, nsIContent* if (!commandDisabled.Equals(menuDisabled)) { // The menu's disabled state needs to be updated to match the command. if (commandDisabled.IsEmpty()) { - mContent->AsElement()->UnsetAttr(kNameSpaceID_None, nsGkAtoms::disabled, true); + mContent->AsElement()->UnsetAttr(kNameSpaceID_None, + nsGkAtoms::disabled, true); } else { - mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::disabled, commandDisabled, - true); + mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::disabled, + commandDisabled, true); } } // now we sync our native menu item with the command DOM node mNativeMenuItem.enabled = !aContent->AsElement()->AttrValueIs( - kNameSpaceID_None, nsGkAtoms::disabled, nsGkAtoms::_true, eCaseMatters); + kNameSpaceID_None, nsGkAtoms::disabled, nsGkAtoms::_true, + eCaseMatters); } } @@ -362,8 +390,10 @@ bool IsMenuStructureElement(nsIContent* aContent) { nsGkAtoms::menuseparator); } -void nsMenuItemX::ObserveContentRemoved(dom::Document* aDocument, nsIContent* aContainer, - nsIContent* aChild, nsIContent* aPreviousSibling) { +void nsMenuItemX::ObserveContentRemoved(dom::Document* aDocument, + nsIContent* aContainer, + nsIContent* aChild, + nsIContent* aPreviousSibling) { MOZ_RELEASE_ASSERT(mMenuGroupOwner); MOZ_RELEASE_ASSERT(mMenuParent); @@ -376,7 +406,8 @@ void nsMenuItemX::ObserveContentRemoved(dom::Document* aDocument, nsIContent* aC } } -void nsMenuItemX::ObserveContentInserted(dom::Document* aDocument, nsIContent* aContainer, +void nsMenuItemX::ObserveContentInserted(dom::Document* aDocument, + nsIContent* aContainer, nsIContent* aChild) { MOZ_RELEASE_ASSERT(mMenuParent); @@ -390,7 +421,8 @@ void nsMenuItemX::ObserveContentInserted(dom::Document* aDocument, nsIContent* a void nsMenuItemX::SetupIcon() { if (mType != eRegularMenuItemType) { - // Don't support icons on checkbox and radio menuitems, for consistency with Windows & Linux. + // Don't support icons on checkbox and radio menuitems, for consistency with + // Windows & Linux. return; } @@ -398,4 +430,6 @@ void nsMenuItemX::SetupIcon() { mNativeMenuItem.image = mIcon->GetIconImage(); } -void nsMenuItemX::IconUpdated() { mNativeMenuItem.image = mIcon->GetIconImage(); } +void nsMenuItemX::IconUpdated() { + mNativeMenuItem.image = mIcon->GetIconImage(); +} diff --git a/widget/cocoa/nsMenuUtilsX.mm b/widget/cocoa/nsMenuUtilsX.mm index aca279d64c1f..f2eea0e54690 100644 --- a/widget/cocoa/nsMenuUtilsX.mm +++ b/widget/cocoa/nsMenuUtilsX.mm @@ -28,7 +28,8 @@ using namespace mozilla; bool nsMenuUtilsX::gIsSynchronouslyActivatingNativeMenuItemDuringTest = false; void nsMenuUtilsX::DispatchCommandTo(nsIContent* aTargetContent, - NSEventModifierFlags aModifierFlags, int16_t aButton) { + NSEventModifierFlags aModifierFlags, + int16_t aButton) { MOZ_ASSERT(aTargetContent, "null ptr"); dom::Document* doc = aTargetContent->OwnerDoc(); @@ -43,8 +44,9 @@ void nsMenuUtilsX::DispatchCommandTo(nsIContent* aTargetContent, IgnoredErrorResult rv; event->InitCommandEvent(u"command"_ns, true, true, - nsGlobalWindowInner::Cast(doc->GetInnerWindow()), 0, ctrlKey, altKey, - shiftKey, cmdKey, aButton, nullptr, 0, rv); + nsGlobalWindowInner::Cast(doc->GetInnerWindow()), 0, + ctrlKey, altKey, shiftKey, cmdKey, aButton, nullptr, + 0, rv); if (!rv.Failed()) { event->SetTrusted(true); aTargetContent->DispatchEvent(*event); @@ -55,17 +57,19 @@ void nsMenuUtilsX::DispatchCommandTo(nsIContent* aTargetContent, NSString* nsMenuUtilsX::GetTruncatedCocoaLabel(const nsString& itemLabel) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; - // We want to truncate long strings to some reasonable pixel length but there is no - // good API for doing that which works for all OS versions and architectures. For now - // we'll do nothing for consistency and depend on good user interface design to limit - // string lengths. - return [NSString stringWithCharacters:reinterpret_cast(itemLabel.get()) - length:itemLabel.Length()]; + // We want to truncate long strings to some reasonable pixel length but there + // is no good API for doing that which works for all OS versions and + // architectures. For now we'll do nothing for consistency and depend on good + // user interface design to limit string lengths. + return [NSString + stringWithCharacters:reinterpret_cast(itemLabel.get()) + length:itemLabel.Length()]; NS_OBJC_END_TRY_ABORT_BLOCK; } -uint8_t nsMenuUtilsX::GeckoModifiersForNodeAttribute(const nsString& modifiersAttribute) { +uint8_t nsMenuUtilsX::GeckoModifiersForNodeAttribute( + const nsString& modifiersAttribute) { uint8_t modifiers = knsMenuItemNoModifier; char* str = ToNewCString(modifiersAttribute); char* newStr; @@ -87,7 +91,8 @@ uint8_t nsMenuUtilsX::GeckoModifiersForNodeAttribute(const nsString& modifiersAt return modifiers; } -unsigned int nsMenuUtilsX::MacModifiersForGeckoModifiers(uint8_t geckoModifiers) { +unsigned int nsMenuUtilsX::MacModifiersForGeckoModifiers( + uint8_t geckoModifiers) { unsigned int macModifiers = 0; if (geckoModifiers & knsMenuItemShiftModifier) { @@ -109,7 +114,8 @@ unsigned int nsMenuUtilsX::MacModifiersForGeckoModifiers(uint8_t geckoModifiers) nsMenuBarX* nsMenuUtilsX::GetHiddenWindowMenuBar() { nsIWidget* hiddenWindowWidgetNoCOMPtr = nsCocoaUtils::GetHiddenWindowWidget(); if (hiddenWindowWidgetNoCOMPtr) { - return static_cast(hiddenWindowWidgetNoCOMPtr)->GetMenuBar(); + return static_cast(hiddenWindowWidgetNoCOMPtr) + ->GetMenuBar(); } return nullptr; } @@ -123,9 +129,9 @@ NSMenuItem* nsMenuUtilsX::GetStandardEditMenuItem() { // app-modal dialogs and Gecko-modal dialogs that open above them. So what // we return here isn't always released before it needs to be added to // another menu. See bmo bug 468393. - NSMenuItem* standardEditMenuItem = [[[NSMenuItem alloc] initWithTitle:@"Edit" - action:nil - keyEquivalent:@""] autorelease]; + NSMenuItem* standardEditMenuItem = + [[[NSMenuItem alloc] initWithTitle:@"Edit" action:nil + keyEquivalent:@""] autorelease]; NSMenu* standardEditMenu = [[NSMenu alloc] initWithTitle:@"Edit"]; standardEditMenuItem.submenu = standardEditMenu; [standardEditMenu release]; @@ -176,9 +182,10 @@ NSMenuItem* nsMenuUtilsX::GetStandardEditMenuItem() { [deleteItem release]; // Add Select All - NSMenuItem* selectAllItem = [[NSMenuItem alloc] initWithTitle:@"Select All" - action:@selector(selectAll:) - keyEquivalent:@"a"]; + NSMenuItem* selectAllItem = + [[NSMenuItem alloc] initWithTitle:@"Select All" + action:@selector(selectAll:) + keyEquivalent:@"a"]; [standardEditMenu addItem:selectAllItem]; [selectAllItem release]; @@ -188,16 +195,19 @@ NSMenuItem* nsMenuUtilsX::GetStandardEditMenuItem() { } bool nsMenuUtilsX::NodeIsHiddenOrCollapsed(nsIContent* aContent) { - return aContent->IsElement() && - (aContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::hidden, nsGkAtoms::_true, - eCaseMatters) || - aContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::collapsed, - nsGkAtoms::_true, eCaseMatters)); + return aContent->IsElement() && (aContent->AsElement()->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::hidden, + nsGkAtoms::_true, eCaseMatters) || + aContent->AsElement()->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::collapsed, + nsGkAtoms::_true, eCaseMatters)); } -NSMenuItem* nsMenuUtilsX::NativeMenuItemWithLocation(NSMenu* aRootMenu, NSString* aLocationString, +NSMenuItem* nsMenuUtilsX::NativeMenuItemWithLocation(NSMenu* aRootMenu, + NSString* aLocationString, bool aIsMenuBar) { - NSArray* indexes = [aLocationString componentsSeparatedByString:@"|"]; + NSArray* indexes = + [aLocationString componentsSeparatedByString:@"|"]; unsigned int pathLength = indexes.count; if (pathLength == 0) { return nil; @@ -207,7 +217,8 @@ NSMenuItem* nsMenuUtilsX::NativeMenuItemWithLocation(NSMenu* aRootMenu, NSString for (unsigned int depth = 0; depth < pathLength; depth++) { NSInteger targetIndex = [indexes objectAtIndex:depth].integerValue; if (aIsMenuBar && depth == 0) { - // We remove the application menu from consideration for the top-level menu. + // We remove the application menu from consideration for the top-level + // menu. targetIndex++; } int itemCount = currentSubmenu.numberOfItems; @@ -230,20 +241,24 @@ NSMenuItem* nsMenuUtilsX::NativeMenuItemWithLocation(NSMenu* aRootMenu, NSString return nil; } -static void CheckNativeMenuConsistencyImpl(NSMenu* aMenu, std::unordered_set& aSeenObjects); +static void CheckNativeMenuConsistencyImpl( + NSMenu* aMenu, std::unordered_set& aSeenObjects); -static void CheckNativeMenuItemConsistencyImpl(NSMenuItem* aMenuItem, - std::unordered_set& aSeenObjects) { +static void CheckNativeMenuItemConsistencyImpl( + NSMenuItem* aMenuItem, std::unordered_set& aSeenObjects) { bool inserted = aSeenObjects.insert(aMenuItem).second; - MOZ_RELEASE_ASSERT(inserted, "Duplicate NSMenuItem object in native menu structure"); + MOZ_RELEASE_ASSERT(inserted, + "Duplicate NSMenuItem object in native menu structure"); if (aMenuItem.hasSubmenu) { CheckNativeMenuConsistencyImpl(aMenuItem.submenu, aSeenObjects); } } -static void CheckNativeMenuConsistencyImpl(NSMenu* aMenu, std::unordered_set& aSeenObjects) { +static void CheckNativeMenuConsistencyImpl( + NSMenu* aMenu, std::unordered_set& aSeenObjects) { bool inserted = aSeenObjects.insert(aMenu).second; - MOZ_RELEASE_ASSERT(inserted, "Duplicate NSMenu object in native menu structure"); + MOZ_RELEASE_ASSERT(inserted, + "Duplicate NSMenu object in native menu structure"); for (NSMenuItem* item in aMenu.itemArray) { CheckNativeMenuItemConsistencyImpl(item, aSeenObjects); } @@ -278,16 +293,20 @@ static void DumpNativeNSMenuItemImpl(NSMenuItem* aItem, uint32_t aIndent, if (aIndexInParentMenu) { printf("[%d] ", *aIndexInParentMenu); } - printf("NSMenuItem [%p] %-16s%s\n", aItem, - aItem.isSeparatorItem ? "----" - : (aItem.title.length == 0 ? "(no title)" : aItem.title.UTF8String), - aItem.hasSubmenu ? " [hasSubmenu]" : ""); + printf( + "NSMenuItem [%p] %-16s%s\n", aItem, + aItem.isSeparatorItem + ? "----" + : (aItem.title.length == 0 ? "(no title)" : aItem.title.UTF8String), + aItem.hasSubmenu ? " [hasSubmenu]" : ""); if (aItem.hasSubmenu) { DumpNativeNSMenuImpl(aItem.submenu, aIndent + 1); } } -void nsMenuUtilsX::DumpNativeMenu(NSMenu* aMenu) { DumpNativeNSMenuImpl(aMenu, 0); } +void nsMenuUtilsX::DumpNativeMenu(NSMenu* aMenu) { + DumpNativeNSMenuImpl(aMenu, 0); +} void nsMenuUtilsX::DumpNativeMenuItem(NSMenuItem* aMenuItem) { DumpNativeNSMenuItemImpl(aMenuItem, 0, Nothing()); diff --git a/widget/cocoa/nsMenuX.mm b/widget/cocoa/nsMenuX.mm index 792730b628da..2a7187f10648 100644 --- a/widget/cocoa/nsMenuX.mm +++ b/widget/cocoa/nsMenuX.mm @@ -57,20 +57,25 @@ static void SwizzleDynamicIndexingMethods() { nsToolkit::SwizzleMethods([NSMenu class], @selector(_addItem:toTable:), @selector(nsMenuX_NSMenu_addItem:toTable:), true); nsToolkit::SwizzleMethods([NSMenu class], @selector(_removeItem:fromTable:), - @selector(nsMenuX_NSMenu_removeItem:fromTable:), true); + @selector(nsMenuX_NSMenu_removeItem:fromTable:), + true); // On SnowLeopard the Shortcut framework (which contains the // SCTGRLIndex class) is loaded on demand, whenever the user first opens // a menu (which normally hasn't happened yet). So we need to load it // here explicitly. - dlopen("/System/Library/PrivateFrameworks/Shortcut.framework/Shortcut", RTLD_LAZY); + dlopen("/System/Library/PrivateFrameworks/Shortcut.framework/Shortcut", + RTLD_LAZY); Class SCTGRLIndexClass = ::NSClassFromString(@"SCTGRLIndex"); - nsToolkit::SwizzleMethods(SCTGRLIndexClass, @selector(indexMenuBarDynamically), - @selector(nsMenuX_SCTGRLIndex_indexMenuBarDynamically)); + nsToolkit::SwizzleMethods( + SCTGRLIndexClass, @selector(indexMenuBarDynamically), + @selector(nsMenuX_SCTGRLIndex_indexMenuBarDynamically)); - Class NSServicesMenuUpdaterClass = ::NSClassFromString(@"_NSServicesMenuUpdater"); - nsToolkit::SwizzleMethods(NSServicesMenuUpdaterClass, - @selector(populateMenu:withServiceEntries:forDisplay:), - @selector(nsMenuX_populateMenu:withServiceEntries:forDisplay:)); + Class NSServicesMenuUpdaterClass = + ::NSClassFromString(@"_NSServicesMenuUpdater"); + nsToolkit::SwizzleMethods( + NSServicesMenuUpdaterClass, + @selector(populateMenu:withServiceEntries:forDisplay:), + @selector(nsMenuX_populateMenu:withServiceEntries:forDisplay:)); gMenuMethodsSwizzled = true; } @@ -79,7 +84,8 @@ static void SwizzleDynamicIndexingMethods() { // nsMenuX // -nsMenuX::nsMenuX(nsMenuParentX* aParent, nsMenuGroupOwnerX* aMenuGroupOwner, nsIContent* aContent) +nsMenuX::nsMenuX(nsMenuParentX* aParent, nsMenuGroupOwnerX* aMenuGroupOwner, + nsIContent* aContent) : mContent(aContent), mParent(aParent), mMenuGroupOwner(aMenuGroupOwner) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; @@ -98,7 +104,8 @@ nsMenuX::nsMenuX(nsMenuParentX* aParent, nsMenuGroupOwnerX* aMenuGroupOwner, nsI } mNativeMenu = CreateMenuWithGeckoString(mLabel); - // register this menu to be notified when changes are made to our content object + // register this menu to be notified when changes are made to our content + // object NS_ASSERTION(mMenuGroupOwner, "No menu owner given, must have one"); mMenuGroupOwner->RegisterForContentChanges(mContent, this); @@ -111,8 +118,9 @@ nsMenuX::nsMenuX(nsMenuParentX* aParent, nsMenuGroupOwnerX* aMenuGroupOwner, nsI mNativeMenuItem.submenu = mNativeMenu; SetEnabled(!mContent->IsElement() || - !mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled, - nsGkAtoms::_true, eCaseMatters)); + !mContent->AsElement()->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::disabled, nsGkAtoms::_true, + eCaseMatters)); // We call RebuildMenu here because keyboard commands are dependent upon // native menu items being created. If we only call RebuildMenu when a menu @@ -168,8 +176,9 @@ nsMenuX::~nsMenuX() { void nsMenuX::DetachFromGroupOwnerRecursive() { if (!mMenuGroupOwner) { // Don't recurse if this subtree is already detached. - // This avoids repeated recursion during the destruction of nested nsMenuX structures. - // Our invariant is: If we are detached, all of our contents are also detached. + // This avoids repeated recursion during the destruction of nested nsMenuX + // structures. Our invariant is: If we are detached, all of our contents are + // also detached. return; } @@ -180,8 +189,13 @@ void nsMenuX::DetachFromGroupOwnerRecursive() { // Also detach all our children. for (auto& child : mMenuChildren) { - child.match([](const RefPtr& aMenu) { aMenu->DetachFromGroupOwnerRecursive(); }, - [](const RefPtr& aMenuItem) { aMenuItem->DetachFromGroupOwner(); }); + child.match( + [](const RefPtr& aMenu) { + aMenu->DetachFromGroupOwnerRecursive(); + }, + [](const RefPtr& aMenuItem) { + aMenuItem->DetachFromGroupOwner(); + }); } } @@ -199,7 +213,8 @@ void nsMenuX::OnMenuDidOpen(dom::Element* aPopupElement) { } } -void nsMenuX::OnMenuWillActivateItem(dom::Element* aPopupElement, dom::Element* aMenuItemElement) { +void nsMenuX::OnMenuWillActivateItem(dom::Element* aPopupElement, + dom::Element* aMenuItemElement) { RefPtr kungFuDeathGrip(this); if (mObserver) { mObserver->OnMenuWillActivateItem(aPopupElement, aMenuItemElement); @@ -219,12 +234,16 @@ void nsMenuX::AddMenuChild(MenuChild&& aChild) { WillInsertChild(aChild); mMenuChildren.AppendElement(aChild); - bool isVisible = - aChild.match([](const RefPtr& aMenu) { return aMenu->IsVisible(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->IsVisible(); }); + bool isVisible = aChild.match( + [](const RefPtr& aMenu) { return aMenu->IsVisible(); }, + [](const RefPtr& aMenuItem) { + return aMenuItem->IsVisible(); + }); NSMenuItem* nativeItem = aChild.match( [](const RefPtr& aMenu) { return aMenu->NativeNSMenuItem(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->NativeNSMenuItem(); }); + [](const RefPtr& aMenuItem) { + return aMenuItem->NativeNSMenuItem(); + }); if (isVisible) { RemovePlaceholderIfPresent(); @@ -242,9 +261,11 @@ void nsMenuX::InsertMenuChild(MenuChild&& aChild) { size_t insertionIndex = FindInsertionIndex(aChild); mMenuChildren.InsertElementAt(insertionIndex, aChild); - bool isVisible = - aChild.match([](const RefPtr& aMenu) { return aMenu->IsVisible(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->IsVisible(); }); + bool isVisible = aChild.match( + [](const RefPtr& aMenu) { return aMenu->IsVisible(); }, + [](const RefPtr& aMenuItem) { + return aMenuItem->IsVisible(); + }); if (isVisible) { MenuChildChangedVisibility(aChild, true); } @@ -253,9 +274,11 @@ void nsMenuX::InsertMenuChild(MenuChild&& aChild) { } void nsMenuX::RemoveMenuChild(const MenuChild& aChild) { - bool isVisible = - aChild.match([](const RefPtr& aMenu) { return aMenu->IsVisible(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->IsVisible(); }); + bool isVisible = aChild.match( + [](const RefPtr& aMenu) { return aMenu->IsVisible(); }, + [](const RefPtr& aMenuItem) { + return aMenuItem->IsVisible(); + }); if (isVisible) { MenuChildChangedVisibility(aChild, false); } @@ -268,16 +291,20 @@ size_t nsMenuX::FindInsertionIndex(const MenuChild& aChild) { nsCOMPtr menuPopup = GetMenuPopupContent(); MOZ_RELEASE_ASSERT(menuPopup); - RefPtr insertedContent = - aChild.match([](const RefPtr& aMenu) { return aMenu->Content(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->Content(); }); + RefPtr insertedContent = aChild.match( + [](const RefPtr& aMenu) { return aMenu->Content(); }, + [](const RefPtr& aMenuItem) { + return aMenuItem->Content(); + }); MOZ_RELEASE_ASSERT(insertedContent->GetParent() == menuPopup); - // Iterate over menuPopup's children (insertedContent's siblings) until we encounter - // insertedContent. At the same time, keep track of the index in mMenuChildren. + // Iterate over menuPopup's children (insertedContent's siblings) until we + // encounter insertedContent. At the same time, keep track of the index in + // mMenuChildren. size_t index = 0; - for (nsIContent* child = menuPopup->GetFirstChild(); child && index < mMenuChildren.Length(); + for (nsIContent* child = menuPopup->GetFirstChild(); + child && index < mMenuChildren.Length(); child = child->GetNextSibling()) { if (child == insertedContent) { break; @@ -285,7 +312,9 @@ size_t nsMenuX::FindInsertionIndex(const MenuChild& aChild) { RefPtr contentAtIndex = mMenuChildren[index].match( [](const RefPtr& aMenu) { return aMenu->Content(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->Content(); }); + [](const RefPtr& aMenuItem) { + return aMenuItem->Content(); + }); if (child == contentAtIndex) { index++; } @@ -313,7 +342,8 @@ nsresult nsMenuX::GetVisibleItemCount(uint32_t& aCount) { } // Only includes visible items. Note that this is provides O(N) access -// If you need to iterate or search, consider using GetItemAt and doing your own filtering +// If you need to iterate or search, consider using GetItemAt and doing your own +// filtering Maybe nsMenuX::GetVisibleItemAt(uint32_t aPos) { uint32_t count = mMenuChildren.Length(); if (aPos >= mVisibleItemsCount || aPos >= count) { @@ -329,9 +359,11 @@ Maybe nsMenuX::GetVisibleItemAt(uint32_t aPos) { uint32_t visibleNodeIndex = 0; for (uint32_t i = 0; i < count; i++) { MenuChild item = *GetItemAt(i); - RefPtr content = - item.match([](const RefPtr& aMenu) { return aMenu->Content(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->Content(); }); + RefPtr content = item.match( + [](const RefPtr& aMenu) { return aMenu->Content(); }, + [](const RefPtr& aMenuItem) { + return aMenuItem->Content(); + }); if (!nsMenuUtilsX::NodeIsHiddenOrCollapsed(content)) { if (aPos == visibleNodeIndex) { // we found the visible node we're looking for, return it @@ -344,11 +376,14 @@ Maybe nsMenuX::GetVisibleItemAt(uint32_t aPos) { return {}; } -Maybe nsMenuX::GetItemForElement(Element* aMenuChildElement) { +Maybe nsMenuX::GetItemForElement( + Element* aMenuChildElement) { for (auto& child : mMenuChildren) { - RefPtr content = - child.match([](const RefPtr& aMenu) { return aMenu->Content(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->Content(); }); + RefPtr content = child.match( + [](const RefPtr& aMenu) { return aMenu->Content(); }, + [](const RefPtr& aMenuItem) { + return aMenuItem->Content(); + }); if (content == aMenuChildElement) { return Some(child); } @@ -397,7 +432,8 @@ void nsMenuX::MenuOpened() { return; } - // Make sure we fire any pending popupshown / popuphiding / popuphidden events first. + // Make sure we fire any pending popupshown / popuphiding / popuphidden events + // first. FlushMenuOpenedRunnable(); FlushMenuClosedRunnable(); @@ -405,10 +441,11 @@ void nsMenuX::MenuOpened() { // Fire popupshowing now. bool approvedToOpen = OnOpen(); if (!approvedToOpen) { - // We can only stop menus from opening which we open ourselves. We cannot stop menubar root - // menus or menu submenus from opening. - // For context menus, we can call OnOpen() before we ask the system to open the menu. - NS_WARNING("The popupshowing event had preventDefault() called on it, but in MenuOpened() it " + // We can only stop menus from opening which we open ourselves. We cannot + // stop menubar root menus or menu submenus from opening. For context + // menus, we can call OnOpen() before we ask the system to open the menu. + NS_WARNING("The popupshowing event had preventDefault() called on it, " + "but in MenuOpened() it " "is too late to stop the menu from opening."); } } @@ -425,10 +462,9 @@ void nsMenuX::MenuOpened() { } // Fire the popupshown event in MenuOpenedAsync. - // MenuOpened() is called during menuWillOpen, and if cancelTracking is called now, menuDidClose - // will not be called. - // The runnable object must not hold a strong reference to the nsMenuX, so that there is no - // reference cycle. + // MenuOpened() is called during menuWillOpen, and if cancelTracking is called + // now, menuDidClose will not be called. The runnable object must not hold a + // strong reference to the nsMenuX, so that there is no reference cycle. class MenuOpenedAsyncRunnable final : public mozilla::CancelableRunnable { public: explicit MenuOpenedAsyncRunnable(nsMenuX* aMenu) @@ -470,7 +506,8 @@ void nsMenuX::MenuOpenedAsync() { // Open the node. if (mContent->IsElement()) { - mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::open, u"true"_ns, true); + mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::open, + u"true"_ns, true); } RefPtr popupContent = GetMenuPopupContent(); @@ -482,7 +519,8 @@ void nsMenuX::MenuOpenedAsync() { // Fire popupshown. nsEventStatus status = nsEventStatus_eIgnore; - WidgetMouseEvent event(true, eXULPopupShown, nullptr, WidgetMouseEvent::eReal); + WidgetMouseEvent event(true, eXULPopupShown, nullptr, + WidgetMouseEvent::eReal); RefPtr dispatchTo = popupContent ? popupContent : mContent; EventDispatcher::Dispatch(dispatchTo, nullptr, &event, nullptr, &status); } @@ -495,7 +533,8 @@ void nsMenuX::MenuClosed() { // Make sure we fire any pending popupshown events first. FlushMenuOpenedRunnable(); - // If any of our submenus were opened programmatically, make sure they get closed first. + // If any of our submenus were opened programmatically, make sure they get + // closed first. for (auto& child : mMenuChildren) { if (child.is>()) { child.as>()->MenuClosed(); @@ -505,11 +544,11 @@ void nsMenuX::MenuClosed() { mIsOpen = false; // Do the rest of the MenuClosed work in MenuClosedAsync. - // MenuClosed() is called from -[NSMenuDelegate menuDidClose:]. If a menuitem was clicked, - // menuDidClose is called *before* menuItemHit for the clicked menu item is called. - // This runnable will be canceled if ~nsMenuX runs before the runnable. - // The runnable object must not hold a strong reference to the nsMenuX, so that there is no - // reference cycle. + // MenuClosed() is called from -[NSMenuDelegate menuDidClose:]. If a menuitem + // was clicked, menuDidClose is called *before* menuItemHit for the clicked + // menu item is called. This runnable will be canceled if ~nsMenuX runs before + // the runnable. The runnable object must not hold a strong reference to the + // nsMenuX, so that there is no reference cycle. class MenuClosedAsyncRunnable final : public mozilla::CancelableRunnable { public: explicit MenuClosedAsyncRunnable(nsMenuX* aMenu) @@ -538,7 +577,8 @@ void nsMenuX::MenuClosed() { } void nsMenuX::FlushMenuClosedRunnable() { - // If any of our submenus have a pending menu closed runnable, make sure those run first. + // If any of our submenus have a pending menu closed runnable, make sure those + // run first. for (auto& child : mMenuChildren) { if (child.is>()) { child.as>()->FlushMenuClosedRunnable(); @@ -569,8 +609,10 @@ void nsMenuX::MenuClosedAsync() { nsCOMPtr dispatchTo = popupContent ? popupContent : mContent; nsEventStatus status = nsEventStatus_eIgnore; - WidgetMouseEvent popupHiding(true, eXULPopupHiding, nullptr, WidgetMouseEvent::eReal); - EventDispatcher::Dispatch(dispatchTo, nullptr, &popupHiding, nullptr, &status); + WidgetMouseEvent popupHiding(true, eXULPopupHiding, nullptr, + WidgetMouseEvent::eReal); + EventDispatcher::Dispatch(dispatchTo, nullptr, &popupHiding, nullptr, + &status); mIsOpenForGecko = false; @@ -578,8 +620,10 @@ void nsMenuX::MenuClosedAsync() { mContent->AsElement()->UnsetAttr(kNameSpaceID_None, nsGkAtoms::open, true); } - WidgetMouseEvent popupHidden(true, eXULPopupHidden, nullptr, WidgetMouseEvent::eReal); - EventDispatcher::Dispatch(dispatchTo, nullptr, &popupHidden, nullptr, &status); + WidgetMouseEvent popupHidden(true, eXULPopupHidden, nullptr, + WidgetMouseEvent::eReal); + EventDispatcher::Dispatch(dispatchTo, nullptr, &popupHidden, nullptr, + &status); // Notify our observer. if (mObserver && popupContent) { @@ -587,17 +631,22 @@ void nsMenuX::MenuClosedAsync() { } } -void nsMenuX::ActivateItemAfterClosing(RefPtr&& aItem, NSEventModifierFlags aModifiers, +void nsMenuX::ActivateItemAfterClosing(RefPtr&& aItem, + NSEventModifierFlags aModifiers, int16_t aButton) { if (mIsOpenForGecko) { - // Queue the event into mPendingCommandEvents. We will call aItem->DoCommand in - // MenuClosedAsync(). We rely on the assumption that MenuClosedAsync will run soon. - mPendingCommandEvents.AppendElement(PendingCommandEvent{std::move(aItem), aModifiers, aButton}); + // Queue the event into mPendingCommandEvents. We will call aItem->DoCommand + // in MenuClosedAsync(). We rely on the assumption that MenuClosedAsync will + // run soon. + mPendingCommandEvents.AppendElement( + PendingCommandEvent{std::move(aItem), aModifiers, aButton}); } else { - // The menu item was activated outside of a regular open / activate / close sequence. - // This happens in multiple cases: - // - When a menu item is activated by a keyboard shortcut while all windows are closed - // (otherwise those shortcuts go through Gecko's manual keyboard handling) + // The menu item was activated outside of a regular open / activate / close + // sequence. This happens in multiple cases: + // - When a menu item is activated by a keyboard shortcut while all windows + // are closed + // (otherwise those shortcuts go through Gecko's manual keyboard + // handling) // - When a menu item in the Dock menu is clicked // - During native menu tests // @@ -610,10 +659,11 @@ bool nsMenuX::Close() { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; if (mDidFirePopupshowingAndIsApprovedToOpen && !mIsOpen) { - // Close is being called right after this menu was opened, but before MenuOpened() had a chance - // to run. Call it here so that we can go through the entire popupshown -> popuphiding -> - // popuphidden sequence. Some callers expect to get a popuphidden event even if they close the - // popup before it was fully open. + // Close is being called right after this menu was opened, but before + // MenuOpened() had a chance to run. Call it here so that we can go through + // the entire popupshown -> popuphiding -> popuphidden sequence. Some + // callers expect to get a popuphidden event even if they close the popup + // before it was fully open. MenuOpened(); } @@ -623,11 +673,12 @@ bool nsMenuX::Close() { if (mIsOpen) { // Close the menu. - // We usually don't get here during normal Firefox usage: If the user closes the menu by - // clicking an item, or by clicking outside the menu, or by pressing escape, then the menu gets - // closed by macOS, and not by a call to nsMenuX::Close(). - // If we do get here, it's usually because we're running an automated test. Close the menu - // without the fade-out animation so that we don't unnecessarily slow down the automated tests. + // We usually don't get here during normal Firefox usage: If the user closes + // the menu by clicking an item, or by clicking outside the menu, or by + // pressing escape, then the menu gets closed by macOS, and not by a call to + // nsMenuX::Close(). If we do get here, it's usually because we're running + // an automated test. Close the menu without the fade-out animation so that + // we don't unnecessarily slow down the automated tests. [mNativeMenu cancelTrackingWithoutAnimation]; MOZMenuOpeningCoordinator.needToUnwindForMenuClosing = YES; @@ -642,7 +693,8 @@ bool nsMenuX::Close() { NS_OBJC_END_TRY_ABORT_BLOCK; } -void nsMenuX::OnHighlightedItemChanged(const Maybe& aNewHighlightedIndex) { +void nsMenuX::OnHighlightedItemChanged( + const Maybe& aNewHighlightedIndex) { if (mHighlightedItemIndex == aNewHighlightedIndex) { return; } @@ -651,16 +703,16 @@ void nsMenuX::OnHighlightedItemChanged(const Maybe& aNewHighlightedInd Maybe target = GetVisibleItemAt(*mHighlightedItemIndex); if (target && target->is>()) { bool handlerCalledPreventDefault; // but we don't actually care - target->as>()->DispatchDOMEvent(u"DOMMenuItemInactive"_ns, - &handlerCalledPreventDefault); + target->as>()->DispatchDOMEvent( + u"DOMMenuItemInactive"_ns, &handlerCalledPreventDefault); } } if (aNewHighlightedIndex) { Maybe target = GetVisibleItemAt(*aNewHighlightedIndex); if (target && target->is>()) { bool handlerCalledPreventDefault; // but we don't actually care - target->as>()->DispatchDOMEvent(u"DOMMenuItemActive"_ns, - &handlerCalledPreventDefault); + target->as>()->DispatchDOMEvent( + u"DOMMenuItemActive"_ns, &handlerCalledPreventDefault); } } mHighlightedItemIndex = aNewHighlightedIndex; @@ -672,21 +724,25 @@ void nsMenuX::OnWillActivateItem(NSMenuItem* aItem) { } if (mMenuGroupOwner && mObserver) { - nsMenuItemX* item = mMenuGroupOwner->GetMenuItemForCommandID(uint32_t(aItem.tag)); + nsMenuItemX* item = + mMenuGroupOwner->GetMenuItemForCommandID(uint32_t(aItem.tag)); if (item && item->Content()->IsElement()) { RefPtr itemElement = item->Content()->AsElement(); if (nsCOMPtr popupContent = GetMenuPopupContent()) { - mObserver->OnMenuWillActivateItem(popupContent->AsElement(), itemElement); + mObserver->OnMenuWillActivateItem(popupContent->AsElement(), + itemElement); } } } } // Flushes style. -static NSUserInterfaceLayoutDirection DirectionForElement(dom::Element* aElement) { - // Get the direction from the computed style so that inheritance into submenus is respected. - // aElement may not have a frame. - RefPtr sc = nsComputedDOMStyle::GetComputedStyle(aElement); +static NSUserInterfaceLayoutDirection DirectionForElement( + dom::Element* aElement) { + // Get the direction from the computed style so that inheritance into submenus + // is respected. aElement may not have a frame. + RefPtr sc = + nsComputedDOMStyle::GetComputedStyle(aElement); if (!sc) { return NSApp.userInterfaceLayoutDirection; } @@ -711,11 +767,13 @@ void nsMenuX::RebuildMenu() { } if (menuPopup->IsElement()) { - mNativeMenu.userInterfaceLayoutDirection = DirectionForElement(menuPopup->AsElement()); + mNativeMenu.userInterfaceLayoutDirection = + DirectionForElement(menuPopup->AsElement()); } // Iterate over the kids - for (nsIContent* child = menuPopup->GetFirstChild(); child; child = child->GetNextSibling()) { + for (nsIContent* child = menuPopup->GetFirstChild(); child; + child = child->GetNextSibling()) { if (Maybe menuChild = CreateMenuChild(child)) { AddMenuChild(std::move(*menuChild)); } @@ -732,9 +790,12 @@ void nsMenuX::InsertPlaceholderIfNeeded() { if ([mNativeMenu numberOfItems] == 0) { MOZ_RELEASE_ASSERT(mVisibleItemsCount == 0); - NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; + NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:@"" + action:nil + keyEquivalent:@""]; item.enabled = NO; - item.view = [[[NSView alloc] initWithFrame:NSMakeRect(0, 0, 150, 1)] autorelease]; + item.view = + [[[NSView alloc] initWithFrame:NSMakeRect(0, 0, 150, 1)] autorelease]; [mNativeMenu addItem:item]; [item release]; } @@ -800,11 +861,13 @@ GeckoNSMenu* nsMenuX::CreateMenuWithGeckoString(nsString& aMenuTitle) { } Maybe nsMenuX::CreateMenuChild(nsIContent* aContent) { - if (aContent->IsAnyOfXULElements(nsGkAtoms::menuitem, nsGkAtoms::menuseparator)) { + if (aContent->IsAnyOfXULElements(nsGkAtoms::menuitem, + nsGkAtoms::menuseparator)) { return Some(MenuChild(CreateMenuItem(aContent))); } if (aContent->IsXULElement(nsGkAtoms::menu)) { - return Some(MenuChild(MakeRefPtr(this, mMenuGroupOwner, aContent))); + return Some( + MenuChild(MakeRefPtr(this, mMenuGroupOwner, aContent))); } return {}; } @@ -821,9 +884,10 @@ RefPtr nsMenuX::CreateMenuItem(nsIContent* aMenuItemContent) { if (aMenuItemContent->IsXULElement(nsGkAtoms::menuseparator)) { itemType = eSeparatorMenuItemType; } else if (aMenuItemContent->IsElement()) { - static Element::AttrValuesArray strings[] = {nsGkAtoms::checkbox, nsGkAtoms::radio, nullptr}; - switch (aMenuItemContent->AsElement()->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::type, - strings, eCaseMatters)) { + static Element::AttrValuesArray strings[] = {nsGkAtoms::checkbox, + nsGkAtoms::radio, nullptr}; + switch (aMenuItemContent->AsElement()->FindAttrValueIn( + kNameSpaceID_None, nsGkAtoms::type, strings, eCaseMatters)) { case 0: itemType = eCheckboxMenuItemType; break; @@ -833,17 +897,20 @@ RefPtr nsMenuX::CreateMenuItem(nsIContent* aMenuItemContent) { } } - return MakeRefPtr(this, menuitemName, itemType, mMenuGroupOwner, aMenuItemContent); + return MakeRefPtr(this, menuitemName, itemType, mMenuGroupOwner, + aMenuItemContent); } -// This menu is about to open. Returns false if the handler wants to stop the opening of the menu. +// This menu is about to open. Returns false if the handler wants to stop the +// opening of the menu. bool nsMenuX::OnOpen() { if (mDidFirePopupshowingAndIsApprovedToOpen) { return true; } if (mIsOpen) { - NS_WARNING("nsMenuX::OnOpen() called while the menu is already considered to be open. This " + NS_WARNING("nsMenuX::OnOpen() called while the menu is already considered " + "to be open. This " "seems odd."); } @@ -854,7 +921,8 @@ bool nsMenuX::OnOpen() { } nsEventStatus status = nsEventStatus_eIgnore; - WidgetMouseEvent event(true, eXULPopupShowing, nullptr, WidgetMouseEvent::eReal); + WidgetMouseEvent event(true, eXULPopupShowing, nullptr, + WidgetMouseEvent::eReal); nsresult rv = NS_OK; RefPtr dispatchTo = popupContent ? popupContent : mContent; @@ -886,9 +954,9 @@ void nsMenuX::DidFirePopupShowing() { } } -// Find the |menupopup| child in the |popup| representing this menu. It should be one -// of a very few children so we won't be iterating over a bazillion menu items to find -// it (so the strcmp won't kill us). +// Find the |menupopup| child in the |popup| representing this menu. It should +// be one of a very few children so we won't be iterating over a bazillion menu +// items to find it (so the strcmp won't kill us). already_AddRefed nsMenuX::GetMenuPopupContent() { // Check to see if we are a "menupopup" node (if we are a native menu). if (mContent->IsXULElement(nsGkAtoms::menupopup)) { @@ -935,7 +1003,8 @@ bool nsMenuX::IsXULWindowMenu(nsIContent* aMenuContent) { // nsChangeObserver // -void nsMenuX::ObserveAttributeChanged(dom::Document* aDocument, nsIContent* aContent, +void nsMenuX::ObserveAttributeChanged(dom::Document* aDocument, + nsIContent* aContent, nsAtom* aAttribute) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; @@ -945,14 +1014,17 @@ void nsMenuX::ObserveAttributeChanged(dom::Document* aDocument, nsIContent* aCon } if (aAttribute == nsGkAtoms::disabled) { - SetEnabled(!mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled, - nsGkAtoms::_true, eCaseMatters)); + SetEnabled(!mContent->AsElement()->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::disabled, nsGkAtoms::_true, + eCaseMatters)); } else if (aAttribute == nsGkAtoms::label) { mContent->AsElement()->GetAttr(nsGkAtoms::label, mLabel); - NSString* newCocoaLabelString = nsMenuUtilsX::GetTruncatedCocoaLabel(mLabel); + NSString* newCocoaLabelString = + nsMenuUtilsX::GetTruncatedCocoaLabel(mLabel); mNativeMenu.title = newCocoaLabelString; mNativeMenuItem.title = newCocoaLabelString; - } else if (aAttribute == nsGkAtoms::hidden || aAttribute == nsGkAtoms::collapsed) { + } else if (aAttribute == nsGkAtoms::hidden || + aAttribute == nsGkAtoms::collapsed) { SetRebuild(true); bool newVisible = !nsMenuUtilsX::NodeIsHiddenOrCollapsed(mContent); @@ -977,8 +1049,9 @@ void nsMenuX::ObserveAttributeChanged(dom::Document* aDocument, nsIContent* aCon NS_OBJC_END_TRY_ABORT_BLOCK; } -void nsMenuX::ObserveContentRemoved(dom::Document* aDocument, nsIContent* aContainer, - nsIContent* aChild, nsIContent* aPreviousSibling) { +void nsMenuX::ObserveContentRemoved(dom::Document* aDocument, + nsIContent* aContainer, nsIContent* aChild, + nsIContent* aPreviousSibling) { if (gConstructingMenu) { return; } @@ -991,7 +1064,8 @@ void nsMenuX::ObserveContentRemoved(dom::Document* aDocument, nsIContent* aConta return; } - // The menu is currently open. Remove the child from mMenuChildren and from our NSMenu. + // The menu is currently open. Remove the child from mMenuChildren and from + // our NSMenu. nsCOMPtr popupContent = GetMenuPopupContent(); if (popupContent && aContainer == popupContent && aChild->IsElement()) { if (Maybe child = GetItemForElement(aChild->AsElement())) { @@ -1000,7 +1074,8 @@ void nsMenuX::ObserveContentRemoved(dom::Document* aDocument, nsIContent* aConta } } -void nsMenuX::ObserveContentInserted(dom::Document* aDocument, nsIContent* aContainer, +void nsMenuX::ObserveContentInserted(dom::Document* aDocument, + nsIContent* aContainer, nsIContent* aChild) { if (gConstructingMenu) { return; @@ -1013,7 +1088,8 @@ void nsMenuX::ObserveContentInserted(dom::Document* aDocument, nsIContent* aCont return; } - // The menu is currently open. Insert the child into mMenuChildren and into our NSMenu. + // The menu is currently open. Insert the child into mMenuChildren and into + // our NSMenu. nsCOMPtr popupContent = GetMenuPopupContent(); if (popupContent && aContainer == popupContent) { if (Maybe child = CreateMenuChild(aChild)) { @@ -1034,22 +1110,27 @@ void nsMenuX::IconUpdated() { } } -void nsMenuX::MenuChildChangedVisibility(const MenuChild& aChild, bool aIsVisible) { +void nsMenuX::MenuChildChangedVisibility(const MenuChild& aChild, + bool aIsVisible) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; NSMenuItem* nativeItem = aChild.match( [](const RefPtr& aMenu) { return aMenu->NativeNSMenuItem(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->NativeNSMenuItem(); }); + [](const RefPtr& aMenuItem) { + return aMenuItem->NativeNSMenuItem(); + }); if (aIsVisible) { - MOZ_RELEASE_ASSERT(!nativeItem.menu, - "The native item should not be in a menu while it is hidden"); + MOZ_RELEASE_ASSERT( + !nativeItem.menu, + "The native item should not be in a menu while it is hidden"); RemovePlaceholderIfPresent(); NSInteger insertionPoint = CalculateNativeInsertionPoint(aChild); [mNativeMenu insertItem:nativeItem atIndex:insertionPoint]; mVisibleItemsCount++; } else { - MOZ_RELEASE_ASSERT([mNativeMenu indexOfItem:nativeItem] != -1, - "The native item should be in this menu while it is visible"); + MOZ_RELEASE_ASSERT( + [mNativeMenu indexOfItem:nativeItem] != -1, + "The native item should be in this menu while it is visible"); [mNativeMenu removeItem:nativeItem]; mVisibleItemsCount--; InsertPlaceholderIfNeeded(); @@ -1067,7 +1148,9 @@ NSInteger nsMenuX::CalculateNativeInsertionPoint(const MenuChild& aChild) { } NSMenuItem* nativeItem = currItem.match( [](const RefPtr& aMenu) { return aMenu->NativeNSMenuItem(); }, - [](const RefPtr& aMenuItem) { return aMenuItem->NativeNSMenuItem(); }); + [](const RefPtr& aMenuItem) { + return aMenuItem->NativeNSMenuItem(); + }); // Only count visible items. if (nativeItem.menu) { insertionPoint++; @@ -1077,9 +1160,10 @@ NSInteger nsMenuX::CalculateNativeInsertionPoint(const MenuChild& aChild) { } void nsMenuX::Dump(uint32_t aIndent) const { - printf("%*s - menu [%p] %-16s <%s>", aIndent * 2, "", this, - mLabel.IsEmpty() ? "(empty label)" : NS_ConvertUTF16toUTF8(mLabel).get(), - NS_ConvertUTF16toUTF8(mContent->NodeName()).get()); + printf( + "%*s - menu [%p] %-16s <%s>", aIndent * 2, "", this, + mLabel.IsEmpty() ? "(empty label)" : NS_ConvertUTF16toUTF8(mLabel).get(), + NS_ConvertUTF16toUTF8(mContent->NodeName()).get()); if (mNeedsRebuild) { printf(" [NeedsRebuild]"); } @@ -1095,8 +1179,11 @@ void nsMenuX::Dump(uint32_t aIndent) const { printf(" (%d visible items)", int(mVisibleItemsCount)); printf("\n"); for (const auto& subitem : mMenuChildren) { - subitem.match([=](const RefPtr& aMenu) { aMenu->Dump(aIndent + 1); }, - [=](const RefPtr& aMenuItem) { aMenuItem->Dump(aIndent + 1); }); + subitem.match( + [=](const RefPtr& aMenu) { aMenu->Dump(aIndent + 1); }, + [=](const RefPtr& aMenuItem) { + aMenuItem->Dump(aIndent + 1); + }); } } @@ -1108,8 +1195,8 @@ void nsMenuX::Dump(uint32_t aIndent) const { - (id)initWithGeckoMenu:(nsMenuX*)geckoMenu { if ((self = [super init])) { - NS_ASSERTION(geckoMenu, - "Cannot initialize native menu delegate with NULL gecko menu! Will crash!"); + NS_ASSERTION(geckoMenu, "Cannot initialize native menu delegate with NULL " + "gecko menu! Will crash!"); mGeckoMenu = geckoMenu; mBlocksToRunWhenOpen = [[NSMutableArray alloc] init]; } @@ -1131,7 +1218,8 @@ void nsMenuX::Dump(uint32_t aIndent) const { } Maybe index = - aItem ? Some(static_cast([aMenu indexOfItem:aItem])) : Nothing(); + aItem ? Some(static_cast([aMenu indexOfItem:aItem])) + : Nothing(); mGeckoMenu->OnHighlightedItemChanged(index); } @@ -1269,7 +1357,8 @@ static NSMutableDictionary* gShadowKeyEquivDB = nil; - (int)removeTable:(NSMapTable*)aTable { if (aTable) { - NSValue* objectToRemove = [mTables member:[NSValue valueWithPointer:aTable]]; + NSValue* objectToRemove = + [mTables member:[NSValue valueWithPointer:aTable]]; if (objectToRemove) { [mTables removeObject:objectToRemove]; } @@ -1281,7 +1370,8 @@ static NSMutableDictionary* gShadowKeyEquivDB = nil; @interface NSMenu (MethodSwizzling) + (void)nsMenuX_NSMenu_addItem:(NSMenuItem*)aItem toTable:(NSMapTable*)aTable; -+ (void)nsMenuX_NSMenu_removeItem:(NSMenuItem*)aItem fromTable:(NSMapTable*)aTable; ++ (void)nsMenuX_NSMenu_removeItem:(NSMenuItem*)aItem + fromTable:(NSMapTable*)aTable; @end @implementation NSMenu (MethodSwizzling) @@ -1304,7 +1394,8 @@ static NSMutableDictionary* gShadowKeyEquivDB = nil; [self nsMenuX_NSMenu_addItem:aItem toTable:aTable]; } -+ (void)nsMenuX_NSMenu_removeItem:(NSMenuItem*)aItem fromTable:(NSMapTable*)aTable { ++ (void)nsMenuX_NSMenu_removeItem:(NSMenuItem*)aItem + fromTable:(NSMapTable*)aTable { [self nsMenuX_NSMenu_removeItem:aItem fromTable:aTable]; if (aItem && aTable) { @@ -1382,7 +1473,9 @@ static NSMutableDictionary* gShadowKeyEquivDB = nil; } } - [self nsMenuX_populateMenu:aMenu withServiceEntries:filteredServices forDisplay:aForDisplay]; + [self nsMenuX_populateMenu:aMenu + withServiceEntries:filteredServices + forDisplay:aForDisplay]; } @end diff --git a/widget/cocoa/nsNativeThemeCocoa.mm b/widget/cocoa/nsNativeThemeCocoa.mm index 46f90bf48472..887cb087480d 100644 --- a/widget/cocoa/nsNativeThemeCocoa.mm +++ b/widget/cocoa/nsNativeThemeCocoa.mm @@ -60,8 +60,8 @@ extern "C" { CG_EXTERN void CGContextSetCTM(CGContextRef, CGAffineTransform); CG_EXTERN void CGContextSetBaseCTM(CGContextRef, CGAffineTransform); typedef CFTypeRef CUIRendererRef; -void CUIDraw(CUIRendererRef r, CGRect rect, CGContextRef ctx, CFDictionaryRef options, - CFDictionaryRef* result); +void CUIDraw(CUIRendererRef r, CGRect rect, CGContextRef ctx, + CFDictionaryRef options, CFDictionaryRef* result); } static bool IsDarkAppearance(NSAppearance* appearance) { @@ -70,7 +70,8 @@ static bool IsDarkAppearance(NSAppearance* appearance) { // Workaround for NSCell control tint drawing // Without this workaround, NSCells are always drawn with the clear control tint -// as long as they're not attached to an NSControl which is a subview of an active window. +// as long as they're not attached to an NSControl which is a subview of an +// active window. // XXXmstange Why doesn't Webkit need this? @implementation NSCell (ControlTintWorkaround) - (int)_realControlTint { @@ -78,16 +79,17 @@ static bool IsDarkAppearance(NSAppearance* appearance) { } @end -// This is the window for our MOZCellDrawView. When an NSCell is drawn, some NSCell implementations -// look at the draw view's window to determine whether the cell should draw with the active look. +// This is the window for our MOZCellDrawView. When an NSCell is drawn, some +// NSCell implementations look at the draw view's window to determine whether +// the cell should draw with the active look. @interface MOZCellDrawWindow : NSWindow @property BOOL cellsShouldLookActive; @end @implementation MOZCellDrawWindow -// Override three different methods, for good measure. The NSCell implementation could call any one -// of them. +// Override three different methods, for good measure. The NSCell implementation +// could call any one of them. - (BOOL)_hasActiveAppearance { return self.cellsShouldLookActive; } @@ -111,7 +113,8 @@ static bool IsDarkAppearance(NSAppearance* appearance) { // drawWithFrame:inView:. What's more, doing so even causes unnecessary // invalidations as soon as we draw a focusring! // This class needs to be an NSControl so that NSTextFieldCell (and -// NSSearchFieldCell, which is a subclass of NSTextFieldCell) draws a focus ring. +// NSSearchFieldCell, which is a subclass of NSTextFieldCell) draws a focus +// ring. @interface MOZCellDrawView : NSControl // Called by NSTreeHeaderCell during drawing. @property BOOL _drawingEndSeparator; @@ -129,7 +132,8 @@ static bool IsDarkAppearance(NSAppearance* appearance) { @end -static void DrawFocusRingForCellIfNeeded(NSCell* aCell, NSRect aWithFrame, NSView* aInView) { +static void DrawFocusRingForCellIfNeeded(NSCell* aCell, NSRect aWithFrame, + NSView* aInView) { if ([aCell showsFirstResponder]) { CGContextRef cgContext = [[NSGraphicsContext currentContext] CGContext]; CGContextSaveGState(cgContext); @@ -148,7 +152,8 @@ static void DrawFocusRingForCellIfNeeded(NSCell* aCell, NSRect aWithFrame, NSVie // for the whole button. The transparency layer is a way to merge the // individual button parts together before the focus ring shape is // calculated. - CGContextBeginTransparencyLayerWithRect(cgContext, NSRectToCGRect(aWithFrame), 0); + CGContextBeginTransparencyLayerWithRect(cgContext, + NSRectToCGRect(aWithFrame), 0); [aCell drawFocusRingMaskWithFrame:aWithFrame inView:aInView]; CGContextEndTransparencyLayer(cgContext); @@ -156,7 +161,8 @@ static void DrawFocusRingForCellIfNeeded(NSCell* aCell, NSRect aWithFrame, NSVie } } -static void DrawCellIncludingFocusRing(NSCell* aCell, NSRect aWithFrame, NSView* aInView) { +static void DrawCellIncludingFocusRing(NSCell* aCell, NSRect aWithFrame, + NSView* aInView) { [aCell drawWithFrame:aWithFrame inView:aInView]; DrawFocusRingForCellIfNeeded(aCell, aWithFrame, aInView); } @@ -229,22 +235,26 @@ static void DrawCellIncludingFocusRing(NSCell* aCell, NSRect aWithFrame, NSView* tdi.max = INT32_MAX; tdi.bounds = NSRectToCGRect(cellFrame); tdi.attributes = mIsHorizontal ? kThemeTrackHorizontal : 0; - tdi.enableState = - [self controlTint] == NSClearControlTint ? kThemeTrackInactive : kThemeTrackActive; + tdi.enableState = [self controlTint] == NSClearControlTint + ? kThemeTrackInactive + : kThemeTrackActive; NSControlSize size = [self controlSize]; if (size == NSControlSizeRegular) { - tdi.kind = mIsIndeterminate ? kThemeLargeIndeterminateBar : kThemeLargeProgressBar; + tdi.kind = + mIsIndeterminate ? kThemeLargeIndeterminateBar : kThemeLargeProgressBar; } else { - NS_ASSERTION(size == NSControlSizeSmall, - "We shouldn't have another size than small and regular for the moment"); - tdi.kind = mIsIndeterminate ? kThemeMediumIndeterminateBar : kThemeMediumProgressBar; + NS_ASSERTION( + size == NSControlSizeSmall, + "We shouldn't have another size than small and regular for the moment"); + tdi.kind = mIsIndeterminate ? kThemeMediumIndeterminateBar + : kThemeMediumProgressBar; } int32_t stepsPerSecond = mIsIndeterminate ? 60 : 30; int32_t milliSecondsPerStep = 1000 / stepsPerSecond; - tdi.trackInfo.progress.phase = - uint8_t(PR_IntervalToMilliseconds(PR_IntervalNow()) / milliSecondsPerStep); + tdi.trackInfo.progress.phase = uint8_t( + PR_IntervalToMilliseconds(PR_IntervalNow()) / milliSecondsPerStep); HIThemeDrawTrack(&tdi, NULL, cgContext, kHIThemeOrientationNormal); } @@ -258,15 +268,17 @@ static void DrawCellIncludingFocusRing(NSCell* aCell, NSRect aWithFrame, NSView* @implementation MOZSearchFieldCell - (instancetype)init { - // We would like to render a search field which has the magnifying glass icon at the start of the - // search field, and no cancel button. - // On 10.12 and 10.13, empty search fields render the magnifying glass icon in the middle of the - // field. So in order to get the icon to show at the start of the field, we need to give the field - // some content. We achieve this with a single space character. + // We would like to render a search field which has the magnifying glass icon + // at the start of the search field, and no cancel button. On 10.12 and 10.13, + // empty search fields render the magnifying glass icon in the middle of the + // field. So in order to get the icon to show at the start of the field, we + // need to give the field some content. We achieve this with a single space + // character. self = [super initTextCell:@" "]; - // However, because the field is now non-empty, by default it shows a cancel button. To hide the - // cancel button, override it with a custom NSButtonCell which renders nothing. + // However, because the field is now non-empty, by default it shows a cancel + // button. To hide the cancel button, override it with a custom NSButtonCell + // which renders nothing. NSButtonCell* invisibleCell = [[NSButtonCell alloc] initImageCell:nil]; invisibleCell.bezeled = NO; invisibleCell.bordered = NO; @@ -284,7 +296,8 @@ static void DrawCellIncludingFocusRing(NSCell* aCell, NSRect aWithFrame, NSView* #define HITHEME_ORIENTATION kHIThemeOrientationNormal -static CGFloat kMaxFocusRingWidth = 0; // initialized by the nsNativeThemeCocoa constructor +static CGFloat kMaxFocusRingWidth = + 0; // initialized by the nsNativeThemeCocoa constructor // These enums are for indexing into the margin array. enum { @@ -336,7 +349,8 @@ static void InflateControlRect(NSRect* rect, NSControlSize cocoaControlSize, rect->size.height += buttonMargins[bottomMargin] + buttonMargins[topMargin]; } -static NSWindow* NativeWindowForFrame(nsIFrame* aFrame, nsIWidget** aTopLevelWidget = NULL) { +static NSWindow* NativeWindowForFrame(nsIFrame* aFrame, + nsIWidget** aTopLevelWidget = NULL) { if (!aFrame) return nil; nsIWidget* widget = aFrame->GetNearestWidget(); @@ -360,7 +374,8 @@ static NSSize WindowButtonsSize(nsIFrame* aFrame) { if (closeButton) { buttonBox = NSUnionRect(buttonBox, [closeButton frame]); } - NSButton* minimizeButton = [window standardWindowButton:NSWindowMiniaturizeButton]; + NSButton* minimizeButton = + [window standardWindowButton:NSWindowMiniaturizeButton]; if (minimizeButton) { buttonBox = NSUnionRect(buttonBox, [minimizeButton frame]); } @@ -397,7 +412,8 @@ static BOOL IsActive(nsIFrame* aFrame, BOOL aIsToolbarControl) { static bool IsInSourceList(nsIFrame* aFrame) { for (nsIFrame* frame = aFrame->GetParent(); frame; frame = nsLayoutUtils::GetCrossDocParentFrameInProcess(frame)) { - if (frame->StyleDisplay()->EffectiveAppearance() == StyleAppearance::MozMacSourceList) { + if (frame->StyleDisplay()->EffectiveAppearance() == + StyleAppearance::MozMacSourceList) { return true; } } @@ -465,18 +481,20 @@ nsNativeThemeCocoa::nsNativeThemeCocoa() : ThemeCocoa(ScrollbarStyle()) { if (XRE_IsParentProcess()) { // Put the cell draw view into a window that is never shown. - // This allows us to convince some NSCell implementations (such as NSButtonCell for default - // buttons) to draw with the active appearance. Another benefit of putting the draw view in a - // window is the fact that it lets NSTextFieldCell (and its subclass NSSearchFieldCell) inherit - // the current NSApplication effectiveAppearance automatically, so the field adapts to Dark Mode - // correctly. - // We don't create this window when the native theme is used in the content process because - // NSWindow creation runs into the sandbox and because we never run default buttons in content + // This allows us to convince some NSCell implementations (such as + // NSButtonCell for default buttons) to draw with the active appearance. + // Another benefit of putting the draw view in a window is the fact that it + // lets NSTextFieldCell (and its subclass NSSearchFieldCell) inherit the + // current NSApplication effectiveAppearance automatically, so the field + // adapts to Dark Mode correctly. We don't create this window when the + // native theme is used in the content process because NSWindow creation + // runs into the sandbox and because we never run default buttons in content // processes anyway. - mCellDrawWindow = [[MOZCellDrawWindow alloc] initWithContentRect:NSZeroRect - styleMask:NSWindowStyleMaskBorderless - backing:NSBackingStoreBuffered - defer:NO]; + mCellDrawWindow = [[MOZCellDrawWindow alloc] + initWithContentRect:NSZeroRect + styleMask:NSWindowStyleMaskBorderless + backing:NSBackingStoreBuffered + defer:NO]; [mCellDrawWindow.contentView addSubview:mCellDrawView]; } @@ -516,8 +534,10 @@ nsNativeThemeCocoa::~nsNativeThemeCocoa() { #define BITMAP_MAX_AREA 500000 static int GetBackingScaleFactorForRendering(CGContextRef cgContext) { - CGAffineTransform ctm = CGContextGetUserSpaceToDeviceSpaceTransform(cgContext); - CGRect transformedUserSpacePixel = CGRectApplyAffineTransform(CGRectMake(0, 0, 1, 1), ctm); + CGAffineTransform ctm = + CGContextGetUserSpaceToDeviceSpaceTransform(cgContext); + CGRect transformedUserSpacePixel = + CGRectApplyAffineTransform(CGRectMake(0, 0, 1, 1), ctm); float maxScale = std::max(fabs(transformedUserSpacePixel.size.width), fabs(transformedUserSpacePixel.size.height)); return maxScale > 1.0 ? 2 : 1; @@ -548,27 +568,33 @@ static int GetBackingScaleFactorForRendering(CGContextRef cgContext) { * asked for isFlipped. Otherwise we'll get drawing bugs on 10.4. * mirrorHorizontal - whether to mirror the cell horizontally */ -static void DrawCellWithScaling(NSCell* cell, CGContextRef cgContext, const HIRect& destRect, - NSControlSize controlSize, NSSize naturalSize, NSSize minimumSize, +static void DrawCellWithScaling(NSCell* cell, CGContextRef cgContext, + const HIRect& destRect, + NSControlSize controlSize, NSSize naturalSize, + NSSize minimumSize, const float marginSet[][3][4], NSView* view, BOOL mirrorHorizontal) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - NSRect drawRect = - NSMakeRect(destRect.origin.x, destRect.origin.y, destRect.size.width, destRect.size.height); + NSRect drawRect = NSMakeRect(destRect.origin.x, destRect.origin.y, + destRect.size.width, destRect.size.height); if (naturalSize.width != 0.0f) drawRect.size.width = naturalSize.width; if (naturalSize.height != 0.0f) drawRect.size.height = naturalSize.height; // Keep aspect ratio when scaling if one dimension is free. if (naturalSize.width == 0.0f && naturalSize.height != 0.0f) - drawRect.size.width = destRect.size.width * naturalSize.height / destRect.size.height; + drawRect.size.width = + destRect.size.width * naturalSize.height / destRect.size.height; if (naturalSize.height == 0.0f && naturalSize.width != 0.0f) - drawRect.size.height = destRect.size.height * naturalSize.width / destRect.size.width; + drawRect.size.height = + destRect.size.height * naturalSize.width / destRect.size.width; // Honor minimum sizes. - if (drawRect.size.width < minimumSize.width) drawRect.size.width = minimumSize.width; - if (drawRect.size.height < minimumSize.height) drawRect.size.height = minimumSize.height; + if (drawRect.size.width < minimumSize.width) + drawRect.size.width = minimumSize.width; + if (drawRect.size.height < minimumSize.height) + drawRect.size.height = minimumSize.height; [NSGraphicsContext saveGraphicsState]; @@ -578,8 +604,10 @@ static void DrawCellWithScaling(NSCell* cell, CGContextRef cgContext, const HIRe InflateControlRect(&drawRect, controlSize, marginSet); NSGraphicsContext* savedContext = [NSGraphicsContext currentContext]; - [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:cgContext - flipped:YES]]; + [NSGraphicsContext + setCurrentContext:[NSGraphicsContext + graphicsContextWithCGContext:cgContext + flipped:YES]]; DrawCellIncludingFocusRing(cell, drawRect, view); @@ -589,11 +617,12 @@ static void DrawCellWithScaling(NSCell* cell, CGContextRef cgContext, const HIRe float h = ceil(drawRect.size.height); NSRect tmpRect = NSMakeRect(kMaxFocusRingWidth, kMaxFocusRingWidth, w, h); - // inflate to figure out the frame we need to tell NSCell to draw in, to get something that's - // 0,0,w,h + // inflate to figure out the frame we need to tell NSCell to draw in, to get + // something that's 0,0,w,h InflateControlRect(&tmpRect, controlSize, marginSet); - // and then, expand by kMaxFocusRingWidth size to make sure we can capture any focus ring + // and then, expand by kMaxFocusRingWidth size to make sure we can capture + // any focus ring w += kMaxFocusRingWidth * 2.0; h += kMaxFocusRingWidth * 2.0; @@ -604,27 +633,33 @@ static void DrawCellWithScaling(NSCell* cell, CGContextRef cgContext, const HIRe (int)w * backingScaleFactor * 4, rgb, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(rgb); - // We need to flip the image twice in order to avoid drawing bugs on 10.4, see bug 465069. - // This is the first flip transform, applied to cgContext. + // We need to flip the image twice in order to avoid drawing bugs on 10.4, + // see bug 465069. This is the first flip transform, applied to cgContext. CGContextScaleCTM(cgContext, 1.0f, -1.0f); - CGContextTranslateCTM(cgContext, 0.0f, -(2.0 * destRect.origin.y + destRect.size.height)); + CGContextTranslateCTM(cgContext, 0.0f, + -(2.0 * destRect.origin.y + destRect.size.height)); if (mirrorHorizontal) { CGContextScaleCTM(cgContext, -1.0f, 1.0f); - CGContextTranslateCTM(cgContext, -(2.0 * destRect.origin.x + destRect.size.width), 0.0f); + CGContextTranslateCTM( + cgContext, -(2.0 * destRect.origin.x + destRect.size.width), 0.0f); } NSGraphicsContext* savedContext = [NSGraphicsContext currentContext]; - [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:ctx - flipped:YES]]; + [NSGraphicsContext + setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:ctx + flipped:YES]]; CGContextScaleCTM(ctx, backingScaleFactor, backingScaleFactor); - // Set the context's "base transform" to in order to get correctly-sized focus rings. - CGContextSetBaseCTM(ctx, CGAffineTransformMakeScale(backingScaleFactor, backingScaleFactor)); + // Set the context's "base transform" to in order to get correctly-sized + // focus rings. + CGContextSetBaseCTM(ctx, CGAffineTransformMakeScale(backingScaleFactor, + backingScaleFactor)); // This is the second flip transform, applied to ctx. CGContextScaleCTM(ctx, 1.0f, -1.0f); - CGContextTranslateCTM(ctx, 0.0f, -(2.0 * tmpRect.origin.y + tmpRect.size.height)); + CGContextTranslateCTM(ctx, 0.0f, + -(2.0 * tmpRect.origin.y + tmpRect.size.height)); DrawCellIncludingFocusRing(cell, tmpRect, view); @@ -637,14 +672,16 @@ static void DrawCellWithScaling(NSCell* cell, CGContextRef cgContext, const HIRe // doesn't extend beyond the overflow rect float xscale = destRect.size.width / drawRect.size.width; float yscale = destRect.size.height / drawRect.size.height; - float scaledFocusRingX = xscale < 1.0f ? kMaxFocusRingWidth * xscale : kMaxFocusRingWidth; - float scaledFocusRingY = yscale < 1.0f ? kMaxFocusRingWidth * yscale : kMaxFocusRingWidth; - CGContextDrawImage( - cgContext, - CGRectMake(destRect.origin.x - scaledFocusRingX, destRect.origin.y - scaledFocusRingY, - destRect.size.width + scaledFocusRingX * 2, - destRect.size.height + scaledFocusRingY * 2), - img); + float scaledFocusRingX = + xscale < 1.0f ? kMaxFocusRingWidth * xscale : kMaxFocusRingWidth; + float scaledFocusRingY = + yscale < 1.0f ? kMaxFocusRingWidth * yscale : kMaxFocusRingWidth; + CGContextDrawImage(cgContext, + CGRectMake(destRect.origin.x - scaledFocusRingX, + destRect.origin.y - scaledFocusRingY, + destRect.size.width + scaledFocusRingX * 2, + destRect.size.height + scaledFocusRingY * 2), + img); CGImageRelease(img); CGContextRelease(ctx); @@ -670,9 +707,9 @@ struct CellRenderSettings { NSSize minimumSizes[3]; // A three-dimensional array, - // with the first dimension being the OS version ([0] 10.6-10.9, [1] 10.10 and above), - // the second being the control size (mini, small, regular), and the third - // being the 4 margin values (left, top, right, bottom). + // with the first dimension being the OS version ([0] 10.6-10.9, [1] 10.10 and + // above), the second being the control size (mini, small, regular), and the + // third being the 4 margin values (left, top, right, bottom). float margins[2][3][4]; }; @@ -685,7 +722,8 @@ struct CellRenderSettings { * tolerance - The tolerance as passed to DrawCellWithSnapping. * NOTE: returns NSControlSizeRegular if all values in 'sizes' are zero. */ -static NSControlSize FindControlSize(CGFloat size, const CGFloat* sizes, CGFloat tolerance) { +static NSControlSize FindControlSize(CGFloat size, const CGFloat* sizes, + CGFloat tolerance) { for (uint32_t i = miniControlSize; i <= regularControlSize; ++i) { if (sizes[i] == 0) { continue; @@ -728,12 +766,16 @@ static NSControlSize FindControlSize(CGFloat size, const CGFloat* sizes, CGFloat * it snaps to the next smaller control size without scaling because unscaled * controls look nicer. */ -static void DrawCellWithSnapping(NSCell* cell, CGContextRef cgContext, const HIRect& destRect, - const CellRenderSettings settings, float verticalAlignFactor, - NSView* view, BOOL mirrorHorizontal, float snapTolerance = 2.0f) { +static void DrawCellWithSnapping(NSCell* cell, CGContextRef cgContext, + const HIRect& destRect, + const CellRenderSettings settings, + float verticalAlignFactor, NSView* view, + BOOL mirrorHorizontal, + float snapTolerance = 2.0f) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - const float rectWidth = destRect.size.width, rectHeight = destRect.size.height; + const float rectWidth = destRect.size.width, + rectHeight = destRect.size.height; const NSSize* sizes = settings.naturalSizes; const NSSize miniSize = sizes[EnumSizeForCocoaSize(NSControlSizeMini)]; const NSSize smallSize = sizes[EnumSizeForCocoaSize(NSControlSizeSmall)]; @@ -741,19 +783,25 @@ static void DrawCellWithSnapping(NSCell* cell, CGContextRef cgContext, const HIR HIRect drawRect = destRect; - CGFloat controlWidths[3] = {miniSize.width, smallSize.width, regularSize.width}; - NSControlSize controlSizeX = FindControlSize(rectWidth, controlWidths, snapTolerance); - CGFloat controlHeights[3] = {miniSize.height, smallSize.height, regularSize.height}; - NSControlSize controlSizeY = FindControlSize(rectHeight, controlHeights, snapTolerance); + CGFloat controlWidths[3] = {miniSize.width, smallSize.width, + regularSize.width}; + NSControlSize controlSizeX = + FindControlSize(rectWidth, controlWidths, snapTolerance); + CGFloat controlHeights[3] = {miniSize.height, smallSize.height, + regularSize.height}; + NSControlSize controlSizeY = + FindControlSize(rectHeight, controlHeights, snapTolerance); NSControlSize controlSize = NSControlSizeRegular; size_t sizeIndex = 0; // At some sizes, don't scale but snap. const NSControlSize smallerControlSize = - EnumSizeForCocoaSize(controlSizeX) < EnumSizeForCocoaSize(controlSizeY) ? controlSizeX - : controlSizeY; - const size_t smallerControlSizeIndex = EnumSizeForCocoaSize(smallerControlSize); + EnumSizeForCocoaSize(controlSizeX) < EnumSizeForCocoaSize(controlSizeY) + ? controlSizeX + : controlSizeY; + const size_t smallerControlSizeIndex = + EnumSizeForCocoaSize(smallerControlSize); const NSSize size = sizes[smallerControlSizeIndex]; float diffWidth = size.width ? rectWidth - size.width : 0.0f; float diffHeight = size.height ? rectHeight - size.height : 0.0f; @@ -766,19 +814,22 @@ static void DrawCellWithSnapping(NSCell* cell, CGContextRef cgContext, const HIR // Resize and center the drawRect. if (sizes[sizeIndex].width) { - drawRect.origin.x += ceil((destRect.size.width - sizes[sizeIndex].width) / 2); + drawRect.origin.x += + ceil((destRect.size.width - sizes[sizeIndex].width) / 2); drawRect.size.width = sizes[sizeIndex].width; } if (sizes[sizeIndex].height) { drawRect.origin.y += - floor((destRect.size.height - sizes[sizeIndex].height) * verticalAlignFactor); + floor((destRect.size.height - sizes[sizeIndex].height) * + verticalAlignFactor); drawRect.size.height = sizes[sizeIndex].height; } } else { // Use the larger control size. - controlSize = EnumSizeForCocoaSize(controlSizeX) > EnumSizeForCocoaSize(controlSizeY) - ? controlSizeX - : controlSizeY; + controlSize = + EnumSizeForCocoaSize(controlSizeX) > EnumSizeForCocoaSize(controlSizeY) + ? controlSizeX + : controlSizeY; sizeIndex = EnumSizeForCocoaSize(controlSize); } @@ -786,8 +837,8 @@ static void DrawCellWithSnapping(NSCell* cell, CGContextRef cgContext, const HIR MOZ_ASSERT(sizeIndex < ArrayLength(settings.minimumSizes)); const NSSize minimumSize = settings.minimumSizes[sizeIndex]; - DrawCellWithScaling(cell, cgContext, drawRect, controlSize, sizes[sizeIndex], minimumSize, - settings.margins, view, mirrorHorizontal); + DrawCellWithScaling(cell, cgContext, drawRect, controlSize, sizes[sizeIndex], + minimumSize, settings.margins, view, mirrorHorizontal); NS_OBJC_END_TRY_IGNORE_BLOCK; } @@ -797,17 +848,22 @@ static void DrawCellWithSnapping(NSCell* cell, CGContextRef cgContext, const HIR @end @interface NSObject (NSAppearanceCoreUIRendering) -- (void)_drawInRect:(CGRect)rect context:(CGContextRef)cgContext options:(id)options; +- (void)_drawInRect:(CGRect)rect + context:(CGContextRef)cgContext + options:(id)options; @end -static void RenderWithCoreUI(CGRect aRect, CGContextRef cgContext, NSDictionary* aOptions, +static void RenderWithCoreUI(CGRect aRect, CGContextRef cgContext, + NSDictionary* aOptions, bool aSkipAreaCheck = false) { - if (!aSkipAreaCheck && aRect.size.width * aRect.size.height > BITMAP_MAX_AREA) { + if (!aSkipAreaCheck && + aRect.size.width * aRect.size.height > BITMAP_MAX_AREA) { return; } NSAppearance* appearance = NSAppearance.currentAppearance; - if (appearance && [appearance respondsToSelector:@selector(_drawInRect:context:options:)]) { + if (appearance && + [appearance respondsToSelector:@selector(_drawInRect:context:options:)]) { // Render through NSAppearance on Mac OS 10.10 and up. This will call // CUIDraw with a CoreUI renderer that will give us the correct 10.10 // style. Calling CUIDraw directly with [NSWindow coreUIRenderer] still @@ -816,7 +872,9 @@ static void RenderWithCoreUI(CGRect aRect, CGContextRef cgContext, NSDictionary* } else { // 10.9 and below CUIRendererRef renderer = - [NSWindow respondsToSelector:@selector(coreUIRenderer)] ? [NSWindow coreUIRenderer] : nil; + [NSWindow respondsToSelector:@selector(coreUIRenderer)] + ? [NSWindow coreUIRenderer] + : nil; CUIDraw(renderer, aRect, cgContext, (CFDictionaryRef)aOptions, NULL); } } @@ -848,10 +906,11 @@ static float VerticalAlignFactor(nsIFrame* aFrame) { } } -static void ApplyControlParamsToNSCell(nsNativeThemeCocoa::ControlParams aControlParams, - NSCell* aCell) { +static void ApplyControlParamsToNSCell( + nsNativeThemeCocoa::ControlParams aControlParams, NSCell* aCell) { [aCell setEnabled:!aControlParams.disabled]; - [aCell setShowsFirstResponder:(aControlParams.focused && !aControlParams.disabled && + [aCell setShowsFirstResponder:(aControlParams.focused && + !aControlParams.disabled && aControlParams.insideActiveWindow)]; [aCell setHighlighted:aControlParams.pressed]; } @@ -859,43 +918,45 @@ static void ApplyControlParamsToNSCell(nsNativeThemeCocoa::ControlParams aContro // These are the sizes that Gecko needs to request to draw if it wants // to get a standard-sized Aqua radio button drawn. Note that the rects // that draw these are actually a little bigger. -static const CellRenderSettings radioSettings = {{ - NSMakeSize(11, 11), // mini - NSMakeSize(13, 13), // small - NSMakeSize(16, 16) // regular - }, - {NSZeroSize, NSZeroSize, NSZeroSize}, - {{ - // Leopard - {0, 0, 0, 0}, // mini - {0, 1, 1, 1}, // small - {0, 0, 0, 0} // regular - }, - { - // Yosemite - {0, 0, 0, 0}, // mini - {1, 1, 1, 2}, // small - {0, 0, 0, 0} // regular - }}}; +static const CellRenderSettings radioSettings = { + { + NSMakeSize(11, 11), // mini + NSMakeSize(13, 13), // small + NSMakeSize(16, 16) // regular + }, + {NSZeroSize, NSZeroSize, NSZeroSize}, + {{ + // Leopard + {0, 0, 0, 0}, // mini + {0, 1, 1, 1}, // small + {0, 0, 0, 0} // regular + }, + { + // Yosemite + {0, 0, 0, 0}, // mini + {1, 1, 1, 2}, // small + {0, 0, 0, 0} // regular + }}}; -static const CellRenderSettings checkboxSettings = {{ - NSMakeSize(11, 11), // mini - NSMakeSize(13, 13), // small - NSMakeSize(16, 16) // regular - }, - {NSZeroSize, NSZeroSize, NSZeroSize}, - {{ - // Leopard - {0, 1, 0, 0}, // mini - {0, 1, 0, 1}, // small - {0, 1, 0, 1} // regular - }, - { - // Yosemite - {0, 1, 0, 0}, // mini - {0, 1, 0, 1}, // small - {0, 1, 0, 1} // regular - }}}; +static const CellRenderSettings checkboxSettings = { + { + NSMakeSize(11, 11), // mini + NSMakeSize(13, 13), // small + NSMakeSize(16, 16) // regular + }, + {NSZeroSize, NSZeroSize, NSZeroSize}, + {{ + // Leopard + {0, 1, 0, 0}, // mini + {0, 1, 0, 1}, // small + {0, 1, 0, 1} // regular + }, + { + // Yosemite + {0, 1, 0, 0}, // mini + {0, 1, 0, 1}, // small + {0, 1, 0, 1} // regular + }}}; static NSControlStateValue CellStateForCheckboxOrRadioState( nsNativeThemeCocoa::CheckboxOrRadioState aState) { @@ -909,55 +970,60 @@ static NSControlStateValue CellStateForCheckboxOrRadioState( } } -void nsNativeThemeCocoa::DrawCheckboxOrRadio(CGContextRef cgContext, bool inCheckbox, - const HIRect& inBoxRect, - const CheckboxOrRadioParams& aParams) { +void nsNativeThemeCocoa::DrawCheckboxOrRadio( + CGContextRef cgContext, bool inCheckbox, const HIRect& inBoxRect, + const CheckboxOrRadioParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; NSButtonCell* cell = inCheckbox ? mCheckboxCell : mRadioButtonCell; ApplyControlParamsToNSCell(aParams.controlParams, cell); [cell setState:CellStateForCheckboxOrRadioState(aParams.state)]; - [cell setControlTint:(aParams.controlParams.insideActiveWindow ? [NSColor currentControlTint] - : NSClearControlTint)]; + [cell setControlTint:(aParams.controlParams.insideActiveWindow + ? [NSColor currentControlTint] + : NSClearControlTint)]; // Ensure that the control is square. float length = std::min(inBoxRect.size.width, inBoxRect.size.height); - HIRect drawRect = CGRectMake(inBoxRect.origin.x + (int)((inBoxRect.size.width - length) / 2.0f), - inBoxRect.origin.y + (int)((inBoxRect.size.height - length) / 2.0f), - length, length); + HIRect drawRect = CGRectMake( + inBoxRect.origin.x + (int)((inBoxRect.size.width - length) / 2.0f), + inBoxRect.origin.y + (int)((inBoxRect.size.height - length) / 2.0f), + length, length); if (mCellDrawWindow) { - mCellDrawWindow.cellsShouldLookActive = aParams.controlParams.insideActiveWindow; + mCellDrawWindow.cellsShouldLookActive = + aParams.controlParams.insideActiveWindow; } - DrawCellWithSnapping(cell, cgContext, drawRect, inCheckbox ? checkboxSettings : radioSettings, + DrawCellWithSnapping(cell, cgContext, drawRect, + inCheckbox ? checkboxSettings : radioSettings, aParams.verticalAlignFactor, mCellDrawView, NO); NS_OBJC_END_TRY_IGNORE_BLOCK; } -static const CellRenderSettings searchFieldSettings = {{ - NSMakeSize(0, 16), // mini - NSMakeSize(0, 19), // small - NSMakeSize(0, 22) // regular - }, - { - NSMakeSize(32, 0), // mini - NSMakeSize(38, 0), // small - NSMakeSize(44, 0) // regular - }, - {{ - // Leopard - {0, 0, 0, 0}, // mini - {0, 0, 0, 0}, // small - {0, 0, 0, 0} // regular - }, - { - // Yosemite - {0, 0, 0, 0}, // mini - {0, 0, 0, 0}, // small - {0, 0, 0, 0} // regular - }}}; +static const CellRenderSettings searchFieldSettings = { + { + NSMakeSize(0, 16), // mini + NSMakeSize(0, 19), // small + NSMakeSize(0, 22) // regular + }, + { + NSMakeSize(32, 0), // mini + NSMakeSize(38, 0), // small + NSMakeSize(44, 0) // regular + }, + {{ + // Leopard + {0, 0, 0, 0}, // mini + {0, 0, 0, 0}, // small + {0, 0, 0, 0} // regular + }, + { + // Yosemite + {0, 0, 0, 0}, // mini + {0, 0, 0, 0}, // small + {0, 0, 0, 0} // regular + }}}; static bool IsToolbarStyleContainer(nsIFrame* aFrame) { nsIContent* content = aFrame->GetContent(); @@ -965,7 +1031,8 @@ static bool IsToolbarStyleContainer(nsIFrame* aFrame) { return false; } - if (content->IsAnyOfXULElements(nsGkAtoms::toolbar, nsGkAtoms::toolbox, nsGkAtoms::statusbar)) { + if (content->IsAnyOfXULElements(nsGkAtoms::toolbar, nsGkAtoms::toolbox, + nsGkAtoms::statusbar)) { return true; } @@ -1001,7 +1068,8 @@ nsNativeThemeCocoa::TextFieldParams nsNativeThemeCocoa::ComputeTextFieldParams( return params; } -void nsNativeThemeCocoa::DrawTextField(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawTextField(CGContextRef cgContext, + const HIRect& inBoxRect, const TextFieldParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -1010,15 +1078,17 @@ void nsNativeThemeCocoa::DrawTextField(CGContextRef cgContext, const HIRect& inB [cell setShowsFirstResponder:aParams.focused]; if (mCellDrawWindow) { - mCellDrawWindow.cellsShouldLookActive = YES; // TODO: propagate correct activeness state + mCellDrawWindow.cellsShouldLookActive = + YES; // TODO: propagate correct activeness state } - DrawCellWithSnapping(cell, cgContext, inBoxRect, searchFieldSettings, aParams.verticalAlignFactor, - mCellDrawView, aParams.rtl); + DrawCellWithSnapping(cell, cgContext, inBoxRect, searchFieldSettings, + aParams.verticalAlignFactor, mCellDrawView, aParams.rtl); NS_OBJC_END_TRY_IGNORE_BLOCK; } -void nsNativeThemeCocoa::DrawSearchField(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawSearchField(CGContextRef cgContext, + const HIRect& inBoxRect, const TextFieldParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -1028,10 +1098,12 @@ void nsNativeThemeCocoa::DrawSearchField(CGContextRef cgContext, const HIRect& i mSearchFieldCell.shouldUseToolbarStyle = aParams.insideToolbar; if (mCellDrawWindow) { - mCellDrawWindow.cellsShouldLookActive = YES; // TODO: propagate correct activeness state + mCellDrawWindow.cellsShouldLookActive = + YES; // TODO: propagate correct activeness state } - DrawCellWithSnapping(mSearchFieldCell, cgContext, inBoxRect, searchFieldSettings, - aParams.verticalAlignFactor, mCellDrawView, aParams.rtl); + DrawCellWithSnapping(mSearchFieldCell, cgContext, inBoxRect, + searchFieldSettings, aParams.verticalAlignFactor, + mCellDrawView, aParams.rtl); NS_OBJC_END_TRY_IGNORE_BLOCK; } @@ -1078,13 +1150,15 @@ nsNativeThemeCocoa::MenuIconParams nsNativeThemeCocoa::ComputeMenuIconParams( MenuIconParams params; params.icon = aIcon; params.disabled = isDisabled; - params.insideActiveMenuItem = !isDisabled && CheckBooleanAttr(aFrame, nsGkAtoms::menuactive); + params.insideActiveMenuItem = + !isDisabled && CheckBooleanAttr(aFrame, nsGkAtoms::menuactive); params.centerHorizontally = true; params.rtl = IsFrameRTL(aFrame); return params; } -void nsNativeThemeCocoa::DrawMenuIcon(CGContextRef cgContext, const CGRect& aRect, +void nsNativeThemeCocoa::DrawMenuIcon(CGContextRef cgContext, + const CGRect& aRect, const MenuIconParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -1095,10 +1169,11 @@ void nsNativeThemeCocoa::DrawMenuIcon(CGContextRef cgContext, const CGRect& aRec CGFloat paddingY = std::max(CGFloat(0.0), aRect.size.height - size.height); CGFloat paddingStartX = std::min(paddingX, kMenuIconIndent); CGFloat paddingEndX = std::max(CGFloat(0.0), paddingX - kMenuIconIndent); - CGRect drawRect = CGRectMake(aRect.origin.x + (aParams.centerHorizontally ? ceil(paddingX / 2) - : aParams.rtl ? paddingEndX - : paddingStartX), - aRect.origin.y + ceil(paddingY / 2), size.width, size.height); + CGRect drawRect = CGRectMake( + aRect.origin.x + (aParams.centerHorizontally ? ceil(paddingX / 2) + : aParams.rtl ? paddingEndX + : paddingStartX), + aRect.origin.y + ceil(paddingY / 2), size.width, size.height); NSString* state; if (aParams.disabled) { @@ -1118,9 +1193,12 @@ void nsNativeThemeCocoa::DrawMenuIcon(CGContextRef cgContext, const CGRect& aRec RenderWithCoreUI( drawRect, cgContext, - [NSDictionary dictionaryWithObjectsAndKeys:@"kCUIBackgroundTypeMenu", @"backgroundTypeKey", - imageName, @"imageNameKey", state, @"state", - @"image", @"widget", [NSNumber numberWithBool:YES], + [NSDictionary dictionaryWithObjectsAndKeys:@"kCUIBackgroundTypeMenu", + @"backgroundTypeKey", + imageName, @"imageNameKey", + state, @"state", @"image", + @"widget", + [NSNumber numberWithBool:YES], @"is.flipped", nil]); #if DRAW_IN_FRAME_DEBUG @@ -1138,12 +1216,14 @@ nsNativeThemeCocoa::MenuItemParams nsNativeThemeCocoa::ComputeMenuItemParams( MenuItemParams params; params.checked = aIsChecked; params.disabled = isDisabled; - params.selected = !isDisabled && CheckBooleanAttr(aFrame, nsGkAtoms::menuactive); + params.selected = + !isDisabled && CheckBooleanAttr(aFrame, nsGkAtoms::menuactive); params.rtl = IsFrameRTL(aFrame); return params; } -void nsNativeThemeCocoa::DrawMenuItem(CGContextRef cgContext, const CGRect& inBoxRect, +void nsNativeThemeCocoa::DrawMenuItem(CGContextRef cgContext, + const CGRect& inBoxRect, const MenuItemParams& aParams) { if (aParams.checked) { MenuIconParams params; @@ -1174,7 +1254,8 @@ nsNativeThemeCocoa::ControlParams nsNativeThemeCocoa::ComputeControlParams( ControlParams params; params.disabled = aEventState.HasState(ElementState::DISABLED); params.insideActiveWindow = FrameIsInActiveWindow(aFrame); - params.pressed = aEventState.HasAllStates(ElementState::ACTIVE | ElementState::HOVER); + params.pressed = + aEventState.HasAllStates(ElementState::ACTIVE | ElementState::HOVER); params.focused = aEventState.HasState(ElementState::FOCUS) && (aEventState.HasState(ElementState::FOCUSRING) || ShouldUnconditionallyDrawFocusRingIfFocused(aFrame)); @@ -1185,53 +1266,59 @@ nsNativeThemeCocoa::ControlParams nsNativeThemeCocoa::ComputeControlParams( static const NSSize kHelpButtonSize = NSMakeSize(20, 20); static const NSSize kDisclosureButtonSize = NSMakeSize(21, 21); -static const CellRenderSettings pushButtonSettings = {{ - NSMakeSize(0, 16), // mini - NSMakeSize(0, 19), // small - NSMakeSize(0, 22) // regular - }, - { - NSMakeSize(18, 0), // mini - NSMakeSize(26, 0), // small - NSMakeSize(30, 0) // regular - }, - {{ - // Leopard - {0, 0, 0, 0}, // mini - {4, 0, 4, 1}, // small - {5, 0, 5, 2} // regular - }, - { - // Yosemite - {0, 0, 0, 0}, // mini - {4, 0, 4, 1}, // small - {5, 0, 5, 2} // regular - }}}; +static const CellRenderSettings pushButtonSettings = { + { + NSMakeSize(0, 16), // mini + NSMakeSize(0, 19), // small + NSMakeSize(0, 22) // regular + }, + { + NSMakeSize(18, 0), // mini + NSMakeSize(26, 0), // small + NSMakeSize(30, 0) // regular + }, + {{ + // Leopard + {0, 0, 0, 0}, // mini + {4, 0, 4, 1}, // small + {5, 0, 5, 2} // regular + }, + { + // Yosemite + {0, 0, 0, 0}, // mini + {4, 0, 4, 1}, // small + {5, 0, 5, 2} // regular + }}}; // The height at which we start doing square buttons instead of rounded buttons -// Rounded buttons look bad if drawn at a height greater than 26, so at that point -// we switch over to doing square buttons which looks fine at any size. +// Rounded buttons look bad if drawn at a height greater than 26, so at that +// point we switch over to doing square buttons which looks fine at any size. #define DO_SQUARE_BUTTON_HEIGHT 26 -void nsNativeThemeCocoa::DrawPushButton(CGContextRef cgContext, const HIRect& inBoxRect, - ButtonType aButtonType, ControlParams aControlParams) { +void nsNativeThemeCocoa::DrawPushButton(CGContextRef cgContext, + const HIRect& inBoxRect, + ButtonType aButtonType, + ControlParams aControlParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; ApplyControlParamsToNSCell(aControlParams, mPushButtonCell); [mPushButtonCell setBezelStyle:NSRoundedBezelStyle]; - mPushButtonCell.keyEquivalent = aButtonType == ButtonType::eDefaultPushButton ? @"\r" : @""; + mPushButtonCell.keyEquivalent = + aButtonType == ButtonType::eDefaultPushButton ? @"\r" : @""; if (mCellDrawWindow) { mCellDrawWindow.cellsShouldLookActive = aControlParams.insideActiveWindow; } - DrawCellWithSnapping(mPushButtonCell, cgContext, inBoxRect, pushButtonSettings, 0.5f, - mCellDrawView, aControlParams.rtl, 1.0f); + DrawCellWithSnapping(mPushButtonCell, cgContext, inBoxRect, + pushButtonSettings, 0.5f, mCellDrawView, + aControlParams.rtl, 1.0f); NS_OBJC_END_TRY_IGNORE_BLOCK; } -void nsNativeThemeCocoa::DrawSquareBezelPushButton(CGContextRef cgContext, const HIRect& inBoxRect, - ControlParams aControlParams) { +void nsNativeThemeCocoa::DrawSquareBezelPushButton( + CGContextRef cgContext, const HIRect& inBoxRect, + ControlParams aControlParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; ApplyControlParamsToNSCell(aControlParams, mPushButtonCell); @@ -1240,13 +1327,15 @@ void nsNativeThemeCocoa::DrawSquareBezelPushButton(CGContextRef cgContext, const if (mCellDrawWindow) { mCellDrawWindow.cellsShouldLookActive = aControlParams.insideActiveWindow; } - DrawCellWithScaling(mPushButtonCell, cgContext, inBoxRect, NSControlSizeRegular, NSZeroSize, - NSMakeSize(14, 0), NULL, mCellDrawView, aControlParams.rtl); + DrawCellWithScaling(mPushButtonCell, cgContext, inBoxRect, + NSControlSizeRegular, NSZeroSize, NSMakeSize(14, 0), NULL, + mCellDrawView, aControlParams.rtl); NS_OBJC_END_TRY_IGNORE_BLOCK; } -void nsNativeThemeCocoa::DrawHelpButton(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawHelpButton(CGContextRef cgContext, + const HIRect& inBoxRect, ControlParams aControlParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -1255,14 +1344,16 @@ void nsNativeThemeCocoa::DrawHelpButton(CGContextRef cgContext, const HIRect& in if (mCellDrawWindow) { mCellDrawWindow.cellsShouldLookActive = aControlParams.insideActiveWindow; } - DrawCellWithScaling(mHelpButtonCell, cgContext, inBoxRect, NSControlSizeRegular, NSZeroSize, - kHelpButtonSize, NULL, mCellDrawView, + DrawCellWithScaling(mHelpButtonCell, cgContext, inBoxRect, + NSControlSizeRegular, NSZeroSize, kHelpButtonSize, NULL, + mCellDrawView, false); // Don't mirror icon in RTL. NS_OBJC_END_TRY_IGNORE_BLOCK; } -void nsNativeThemeCocoa::DrawDisclosureButton(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawDisclosureButton(CGContextRef cgContext, + const HIRect& inBoxRect, ControlParams aControlParams, NSControlStateValue aCellState) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -1273,18 +1364,22 @@ void nsNativeThemeCocoa::DrawDisclosureButton(CGContextRef cgContext, const HIRe if (mCellDrawWindow) { mCellDrawWindow.cellsShouldLookActive = aControlParams.insideActiveWindow; } - DrawCellWithScaling(mDisclosureButtonCell, cgContext, inBoxRect, NSControlSizeRegular, NSZeroSize, - kDisclosureButtonSize, NULL, mCellDrawView, + DrawCellWithScaling(mDisclosureButtonCell, cgContext, inBoxRect, + NSControlSizeRegular, NSZeroSize, kDisclosureButtonSize, + NULL, mCellDrawView, false); // Don't mirror icon in RTL. NS_OBJC_END_TRY_IGNORE_BLOCK; } -typedef void (*RenderHIThemeControlFunction)(CGContextRef cgContext, const HIRect& aRenderRect, +typedef void (*RenderHIThemeControlFunction)(CGContextRef cgContext, + const HIRect& aRenderRect, void* aData); -static void RenderTransformedHIThemeControl(CGContextRef aCGContext, const HIRect& aRect, - RenderHIThemeControlFunction aFunc, void* aData, +static void RenderTransformedHIThemeControl(CGContextRef aCGContext, + const HIRect& aRect, + RenderHIThemeControlFunction aFunc, + void* aData, BOOL mirrorHorizontally = NO) { CGAffineTransform savedCTM = CGContextGetCTM(aCGContext); CGContextTranslateCTM(aCGContext, aRect.origin.x, aRect.origin.y); @@ -1293,8 +1388,8 @@ static void RenderTransformedHIThemeControl(CGContextRef aCGContext, const HIRec HIRect drawRect = aRect; drawRect.origin = CGPointZero; - if (!mirrorHorizontally && savedCTM.a == 1.0f && savedCTM.b == 0.0f && savedCTM.c == 0.0f && - (savedCTM.d == 1.0f || savedCTM.d == -1.0f)) { + if (!mirrorHorizontally && savedCTM.a == 1.0f && savedCTM.b == 0.0f && + savedCTM.c == 0.0f && (savedCTM.d == 1.0f || savedCTM.d == -1.0f)) { drawDirect = TRUE; } else { drawDirect = FALSE; @@ -1312,16 +1407,18 @@ static void RenderTransformedHIThemeControl(CGContextRef aCGContext, const HIRec int backingScaleFactor = GetBackingScaleFactorForRendering(aCGContext); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef bitmapctx = CGBitmapContextCreate( - NULL, w * backingScaleFactor, h * backingScaleFactor, 8, w * backingScaleFactor * 4, - colorSpace, kCGImageAlphaPremultipliedFirst); + NULL, w * backingScaleFactor, h * backingScaleFactor, 8, + w * backingScaleFactor * 4, colorSpace, + kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextScaleCTM(bitmapctx, backingScaleFactor, backingScaleFactor); CGContextTranslateCTM(bitmapctx, kMaxFocusRingWidth, kMaxFocusRingWidth); - // Set the context's "base transform" to in order to get correctly-sized focus rings. - CGContextSetBaseCTM(bitmapctx, - CGAffineTransformMakeScale(backingScaleFactor, backingScaleFactor)); + // Set the context's "base transform" to in order to get correctly-sized + // focus rings. + CGContextSetBaseCTM(bitmapctx, CGAffineTransformMakeScale( + backingScaleFactor, backingScaleFactor)); // HITheme always wants to draw into a flipped context, or things // get confused. @@ -1334,7 +1431,8 @@ static void RenderTransformedHIThemeControl(CGContextRef aCGContext, const HIRec CGAffineTransform ctm = CGContextGetCTM(aCGContext); - // We need to unflip, so that we can do a DrawImage without getting a flipped image. + // We need to unflip, so that we can do a DrawImage without getting a + // flipped image. CGContextTranslateCTM(aCGContext, 0.0f, aRect.size.height); CGContextScaleCTM(aCGContext, 1.0f, -1.0f); @@ -1343,7 +1441,8 @@ static void RenderTransformedHIThemeControl(CGContextRef aCGContext, const HIRec CGContextScaleCTM(aCGContext, -1.0f, 1.0f); } - HIRect inflatedDrawRect = CGRectMake(-kMaxFocusRingWidth, -kMaxFocusRingWidth, w, h); + HIRect inflatedDrawRect = + CGRectMake(-kMaxFocusRingWidth, -kMaxFocusRingWidth, w, h); CGContextDrawImage(aCGContext, inflatedDrawRect, bitmap); CGContextSetCTM(aCGContext, ctm); @@ -1355,12 +1454,15 @@ static void RenderTransformedHIThemeControl(CGContextRef aCGContext, const HIRec CGContextSetCTM(aCGContext, savedCTM); } -static void RenderButton(CGContextRef cgContext, const HIRect& aRenderRect, void* aData) { +static void RenderButton(CGContextRef cgContext, const HIRect& aRenderRect, + void* aData) { HIThemeButtonDrawInfo* bdi = (HIThemeButtonDrawInfo*)aData; - HIThemeDrawButton(&aRenderRect, bdi, cgContext, kHIThemeOrientationNormal, NULL); + HIThemeDrawButton(&aRenderRect, bdi, cgContext, kHIThemeOrientationNormal, + NULL); } -static ThemeDrawState ToThemeDrawState(const nsNativeThemeCocoa::ControlParams& aParams) { +static ThemeDrawState ToThemeDrawState( + const nsNativeThemeCocoa::ControlParams& aParams) { if (aParams.disabled) { return kThemeStateUnavailable; } @@ -1370,10 +1472,10 @@ static ThemeDrawState ToThemeDrawState(const nsNativeThemeCocoa::ControlParams& return kThemeStateActive; } -void nsNativeThemeCocoa::DrawHIThemeButton(CGContextRef cgContext, const HIRect& aRect, - ThemeButtonKind aKind, ThemeButtonValue aValue, - ThemeDrawState aState, ThemeButtonAdornment aAdornment, - const ControlParams& aParams) { +void nsNativeThemeCocoa::DrawHIThemeButton( + CGContextRef cgContext, const HIRect& aRect, ThemeButtonKind aKind, + ThemeButtonValue aValue, ThemeDrawState aState, + ThemeButtonAdornment aAdornment, const ControlParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; HIThemeButtonDrawInfo bdi; @@ -1387,7 +1489,8 @@ void nsNativeThemeCocoa::DrawHIThemeButton(CGContextRef cgContext, const HIRect& bdi.adornment |= kThemeAdornmentFocus; } - RenderTransformedHIThemeControl(cgContext, aRect, RenderButton, &bdi, aParams.rtl); + RenderTransformedHIThemeControl(cgContext, aRect, RenderButton, &bdi, + aParams.rtl); #if DRAW_IN_FRAME_DEBUG CGContextSetRGBFillColor(cgContext, 0.0, 0.0, 0.5, 0.25); @@ -1397,7 +1500,8 @@ void nsNativeThemeCocoa::DrawHIThemeButton(CGContextRef cgContext, const HIRect& NS_OBJC_END_TRY_IGNORE_BLOCK; } -void nsNativeThemeCocoa::DrawButton(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawButton(CGContextRef cgContext, + const HIRect& inBoxRect, const ButtonParams& aParams) { ControlParams controlParams = aParams.controlParams; @@ -1411,18 +1515,21 @@ void nsNativeThemeCocoa::DrawButton(CGContextRef cgContext, const HIRect& inBoxR return; case ButtonType::eArrowButton: DrawHIThemeButton(cgContext, inBoxRect, kThemeArrowButton, kThemeButtonOn, - kThemeStateUnavailable, kThemeAdornmentArrowDownArrow, controlParams); + kThemeStateUnavailable, kThemeAdornmentArrowDownArrow, + controlParams); return; case ButtonType::eHelpButton: DrawHelpButton(cgContext, inBoxRect, controlParams); return; case ButtonType::eTreeTwistyPointingRight: - DrawHIThemeButton(cgContext, inBoxRect, kThemeDisclosureButton, kThemeDisclosureRight, - ToThemeDrawState(controlParams), kThemeAdornmentNone, controlParams); + DrawHIThemeButton(cgContext, inBoxRect, kThemeDisclosureButton, + kThemeDisclosureRight, ToThemeDrawState(controlParams), + kThemeAdornmentNone, controlParams); return; case ButtonType::eTreeTwistyPointingDown: - DrawHIThemeButton(cgContext, inBoxRect, kThemeDisclosureButton, kThemeDisclosureDown, - ToThemeDrawState(controlParams), kThemeAdornmentNone, controlParams); + DrawHIThemeButton(cgContext, inBoxRect, kThemeDisclosureButton, + kThemeDisclosureDown, ToThemeDrawState(controlParams), + kThemeAdornmentNone, controlParams); return; case ButtonType::eDisclosureButtonClosed: DrawDisclosureButton(cgContext, inBoxRect, controlParams, NSOffState); @@ -1433,8 +1540,9 @@ void nsNativeThemeCocoa::DrawButton(CGContextRef cgContext, const HIRect& inBoxR } } -nsNativeThemeCocoa::TreeHeaderCellParams nsNativeThemeCocoa::ComputeTreeHeaderCellParams( - nsIFrame* aFrame, ElementState aEventState) { +nsNativeThemeCocoa::TreeHeaderCellParams +nsNativeThemeCocoa::ComputeTreeHeaderCellParams(nsIFrame* aFrame, + ElementState aEventState) { TreeHeaderCellParams params; params.controlParams = ComputeControlParams(aFrame, aEventState); params.sortDirection = GetTreeSortDirection(aFrame); @@ -1451,8 +1559,9 @@ nsNativeThemeCocoa::TreeHeaderCellParams nsNativeThemeCocoa::ComputeTreeHeaderCe highlightForSort:(BOOL)arg5; @end -void nsNativeThemeCocoa::DrawTreeHeaderCell(CGContextRef cgContext, const HIRect& inBoxRect, - const TreeHeaderCellParams& aParams) { +void nsNativeThemeCocoa::DrawTreeHeaderCell( + CGContextRef cgContext, const HIRect& inBoxRect, + const TreeHeaderCellParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; // Without clearing the cell's title, it takes on a default value of "Field", @@ -1460,8 +1569,10 @@ void nsNativeThemeCocoa::DrawTreeHeaderCell(CGContextRef cgContext, const HIRect NSCell* cell = (NSCell*)mTreeHeaderCell; cell.title = @""; - if ([mTreeHeaderCell respondsToSelector:@selector - (_setSortable:showSortIndicator:ascending:priority:highlightForSort:)]) { + if ([mTreeHeaderCell + respondsToSelector:@selector + (_setSortable: + showSortIndicator:ascending:priority:highlightForSort:)]) { switch (aParams.sortDirection) { case eTreeSortDirection_Ascending: [mTreeHeaderCell _setSortable:YES @@ -1490,13 +1601,14 @@ void nsNativeThemeCocoa::DrawTreeHeaderCell(CGContextRef cgContext, const HIRect mTreeHeaderCell.enabled = !aParams.controlParams.disabled; mTreeHeaderCell.state = - (mTreeHeaderCell.enabled && aParams.controlParams.pressed) ? NSOnState : NSOffState; + (mTreeHeaderCell.enabled && aParams.controlParams.pressed) ? NSOnState + : NSOffState; mCellDrawView._drawingEndSeparator = !aParams.lastTreeHeaderCell; NSGraphicsContext* savedContext = NSGraphicsContext.currentContext; - NSGraphicsContext.currentContext = [NSGraphicsContext graphicsContextWithCGContext:cgContext - flipped:YES]; + NSGraphicsContext.currentContext = + [NSGraphicsContext graphicsContextWithCGContext:cgContext flipped:YES]; DrawCellIncludingFocusRing(mTreeHeaderCell, inBoxRect, mCellDrawView); NSGraphicsContext.currentContext = savedContext; @@ -1508,58 +1620,62 @@ void nsNativeThemeCocoa::DrawTreeHeaderCell(CGContextRef cgContext, const HIRect NS_OBJC_END_TRY_IGNORE_BLOCK; } -static const CellRenderSettings dropdownSettings = {{ - NSMakeSize(0, 16), // mini - NSMakeSize(0, 19), // small - NSMakeSize(0, 22) // regular - }, - { - NSMakeSize(18, 0), // mini - NSMakeSize(38, 0), // small - NSMakeSize(44, 0) // regular - }, - {{ - // Leopard - {1, 1, 2, 1}, // mini - {3, 0, 3, 1}, // small - {3, 0, 3, 0} // regular - }, - { - // Yosemite - {1, 1, 2, 1}, // mini - {3, 0, 3, 1}, // small - {3, 0, 3, 0} // regular - }}}; +static const CellRenderSettings dropdownSettings = { + { + NSMakeSize(0, 16), // mini + NSMakeSize(0, 19), // small + NSMakeSize(0, 22) // regular + }, + { + NSMakeSize(18, 0), // mini + NSMakeSize(38, 0), // small + NSMakeSize(44, 0) // regular + }, + {{ + // Leopard + {1, 1, 2, 1}, // mini + {3, 0, 3, 1}, // small + {3, 0, 3, 0} // regular + }, + { + // Yosemite + {1, 1, 2, 1}, // mini + {3, 0, 3, 1}, // small + {3, 0, 3, 0} // regular + }}}; -static const CellRenderSettings editableMenulistSettings = {{ - NSMakeSize(0, 15), // mini - NSMakeSize(0, 18), // small - NSMakeSize(0, 21) // regular - }, - { - NSMakeSize(18, 0), // mini - NSMakeSize(38, 0), // small - NSMakeSize(44, 0) // regular - }, - {{ - // Leopard - {0, 0, 2, 2}, // mini - {0, 0, 3, 2}, // small - {0, 1, 3, 3} // regular - }, - { - // Yosemite - {0, 0, 2, 2}, // mini - {0, 0, 3, 2}, // small - {0, 1, 3, 3} // regular - }}}; +static const CellRenderSettings editableMenulistSettings = { + { + NSMakeSize(0, 15), // mini + NSMakeSize(0, 18), // small + NSMakeSize(0, 21) // regular + }, + { + NSMakeSize(18, 0), // mini + NSMakeSize(38, 0), // small + NSMakeSize(44, 0) // regular + }, + {{ + // Leopard + {0, 0, 2, 2}, // mini + {0, 0, 3, 2}, // small + {0, 1, 3, 3} // regular + }, + { + // Yosemite + {0, 0, 2, 2}, // mini + {0, 0, 3, 2}, // small + {0, 1, 3, 3} // regular + }}}; -void nsNativeThemeCocoa::DrawDropdown(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawDropdown(CGContextRef cgContext, + const HIRect& inBoxRect, const DropdownParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; [mDropdownCell setPullsDown:aParams.pullsDown]; - NSCell* cell = aParams.editable ? (NSCell*)mComboBoxCell : (NSCell*)mDropdownCell; + NSCell* cell = + aParams.editable ? (NSCell*)mComboBoxCell : (NSCell*)mDropdownCell; ApplyControlParamsToNSCell(aParams.controlParams, cell); @@ -1573,22 +1689,25 @@ void nsNativeThemeCocoa::DrawDropdown(CGContextRef cgContext, const HIRect& inBo aParams.editable ? editableMenulistSettings : dropdownSettings; if (mCellDrawWindow) { - mCellDrawWindow.cellsShouldLookActive = aParams.controlParams.insideActiveWindow; + mCellDrawWindow.cellsShouldLookActive = + aParams.controlParams.insideActiveWindow; } - DrawCellWithSnapping(cell, cgContext, inBoxRect, settings, 0.5f, mCellDrawView, - aParams.controlParams.rtl); + DrawCellWithSnapping(cell, cgContext, inBoxRect, settings, 0.5f, + mCellDrawView, aParams.controlParams.rtl); NS_OBJC_END_TRY_IGNORE_BLOCK; } static const CellRenderSettings spinnerSettings = { { - NSMakeSize(11, 16), // mini (width trimmed by 2px to reduce blank border) + NSMakeSize(11, + 16), // mini (width trimmed by 2px to reduce blank border) NSMakeSize(15, 22), // small NSMakeSize(19, 27) // regular }, { - NSMakeSize(11, 16), // mini (width trimmed by 2px to reduce blank border) + NSMakeSize(11, + 16), // mini (width trimmed by 2px to reduce blank border) NSMakeSize(15, 22), // small NSMakeSize(19, 27) // regular }, @@ -1605,8 +1724,8 @@ static const CellRenderSettings spinnerSettings = { {0, 0, 0, 0} // regular }}}; -HIThemeButtonDrawInfo nsNativeThemeCocoa::SpinButtonDrawInfo(ThemeButtonKind aKind, - const SpinButtonParams& aParams) { +HIThemeButtonDrawInfo nsNativeThemeCocoa::SpinButtonDrawInfo( + ThemeButtonKind aKind, const SpinButtonParams& aParams) { HIThemeButtonDrawInfo bdi; bdi.version = 0; bdi.kind = aKind; @@ -1628,7 +1747,8 @@ HIThemeButtonDrawInfo nsNativeThemeCocoa::SpinButtonDrawInfo(ThemeButtonKind aKi return bdi; } -void nsNativeThemeCocoa::DrawSpinButtons(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawSpinButtons(CGContextRef cgContext, + const HIRect& inBoxRect, const SpinButtonParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -1638,11 +1758,14 @@ void nsNativeThemeCocoa::DrawSpinButtons(CGContextRef cgContext, const HIRect& i NS_OBJC_END_TRY_IGNORE_BLOCK; } -void nsNativeThemeCocoa::DrawSpinButton(CGContextRef cgContext, const HIRect& inBoxRect, - SpinButton aDrawnButton, const SpinButtonParams& aParams) { +void nsNativeThemeCocoa::DrawSpinButton(CGContextRef cgContext, + const HIRect& inBoxRect, + SpinButton aDrawnButton, + const SpinButtonParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; - HIThemeButtonDrawInfo bdi = SpinButtonDrawInfo(kThemeIncDecButtonMini, aParams); + HIThemeButtonDrawInfo bdi = + SpinButtonDrawInfo(kThemeIncDecButtonMini, aParams); // Cocoa only allows kThemeIncDecButton to paint the up and down spin buttons // together as a single unit (presumably because when one button is active, @@ -1755,7 +1878,8 @@ nsNativeThemeCocoa::ProgressParams nsNativeThemeCocoa::ComputeProgressParams( return params; } -void nsNativeThemeCocoa::DrawProgress(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawProgress(CGContextRef cgContext, + const HIRect& inBoxRect, const ProgressParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -1765,39 +1889,43 @@ void nsNativeThemeCocoa::DrawProgress(CGContextRef cgContext, const HIRect& inBo [cell setMax:aParams.max]; [cell setIndeterminate:aParams.indeterminate]; [cell setHorizontal:aParams.horizontal]; - [cell setControlTint:(aParams.insideActiveWindow ? [NSColor currentControlTint] - : NSClearControlTint)]; + [cell + setControlTint:(aParams.insideActiveWindow ? [NSColor currentControlTint] + : NSClearControlTint)]; if (mCellDrawWindow) { mCellDrawWindow.cellsShouldLookActive = aParams.insideActiveWindow; } - DrawCellWithSnapping(cell, cgContext, inBoxRect, - progressSettings[aParams.horizontal][aParams.indeterminate], - aParams.verticalAlignFactor, mCellDrawView, aParams.rtl); + DrawCellWithSnapping( + cell, cgContext, inBoxRect, + progressSettings[aParams.horizontal][aParams.indeterminate], + aParams.verticalAlignFactor, mCellDrawView, aParams.rtl); NS_OBJC_END_TRY_IGNORE_BLOCK; } -static const CellRenderSettings meterSetting = {{ - NSMakeSize(0, 16), // mini - NSMakeSize(0, 16), // small - NSMakeSize(0, 16) // regular - }, - {NSZeroSize, NSZeroSize, NSZeroSize}, - {{ - // Leopard - {1, 1, 1, 1}, // mini - {1, 1, 1, 1}, // small - {1, 1, 1, 1} // regular - }, - { - // Yosemite - {1, 1, 1, 1}, // mini - {1, 1, 1, 1}, // small - {1, 1, 1, 1} // regular - }}}; +static const CellRenderSettings meterSetting = { + { + NSMakeSize(0, 16), // mini + NSMakeSize(0, 16), // small + NSMakeSize(0, 16) // regular + }, + {NSZeroSize, NSZeroSize, NSZeroSize}, + {{ + // Leopard + {1, 1, 1, 1}, // mini + {1, 1, 1, 1}, // small + {1, 1, 1, 1} // regular + }, + { + // Yosemite + {1, 1, 1, 1}, // mini + {1, 1, 1, 1}, // small + {1, 1, 1, 1} // regular + }}}; -nsNativeThemeCocoa::MeterParams nsNativeThemeCocoa::ComputeMeterParams(nsIFrame* aFrame) { +nsNativeThemeCocoa::MeterParams nsNativeThemeCocoa::ComputeMeterParams( + nsIFrame* aFrame) { nsIContent* content = aFrame->GetContent(); if (!(content && content->IsHTMLElement(nsGkAtoms::meter))) { return MeterParams(); @@ -1821,7 +1949,8 @@ nsNativeThemeCocoa::MeterParams nsNativeThemeCocoa::ComputeMeterParams(nsIFrame* return params; } -void nsNativeThemeCocoa::DrawMeter(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawMeter(CGContextRef cgContext, + const HIRect& inBoxRect, const MeterParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK @@ -1877,21 +2006,25 @@ void nsNativeThemeCocoa::DrawMeter(CGContextRef cgContext, const HIRect& inBoxRe CGContextTranslateCTM(cgContext, CGRectGetMidX(rect), CGRectGetMidY(rect)); CGContextRotateCTM(cgContext, -M_PI / 2.f); - CGContextTranslateCTM(cgContext, -CGRectGetMidX(rect), -CGRectGetMidY(rect)); + CGContextTranslateCTM(cgContext, -CGRectGetMidX(rect), + -CGRectGetMidY(rect)); } if (mCellDrawWindow) { - mCellDrawWindow.cellsShouldLookActive = YES; // TODO: propagate correct activeness state + mCellDrawWindow.cellsShouldLookActive = + YES; // TODO: propagate correct activeness state } - DrawCellWithSnapping(cell, cgContext, rect, meterSetting, aParams.verticalAlignFactor, - mCellDrawView, !vertical && aParams.rtl); + DrawCellWithSnapping(cell, cgContext, rect, meterSetting, + aParams.verticalAlignFactor, mCellDrawView, + !vertical && aParams.rtl); CGContextRestoreGState(cgContext); NS_OBJC_END_TRY_IGNORE_BLOCK } -void nsNativeThemeCocoa::DrawTabPanel(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawTabPanel(CGContextRef cgContext, + const HIRect& inBoxRect, bool aIsInsideActiveWindow) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -1908,8 +2041,9 @@ void nsNativeThemeCocoa::DrawTabPanel(CGContextRef cgContext, const HIRect& inBo NS_OBJC_END_TRY_IGNORE_BLOCK; } -Maybe nsNativeThemeCocoa::ComputeHTMLScaleParams( - nsIFrame* aFrame, ElementState aEventState) { +Maybe +nsNativeThemeCocoa::ComputeHTMLScaleParams(nsIFrame* aFrame, + ElementState aEventState) { nsRangeFrame* rangeFrame = do_QueryFrame(aFrame); if (!rangeFrame) { return Nothing(); @@ -1931,7 +2065,8 @@ Maybe nsNativeThemeCocoa::ComputeHTMLScaleParam return Some(params); } -void nsNativeThemeCocoa::DrawScale(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawScale(CGContextRef cgContext, + const HIRect& inBoxRect, const ScaleParams& aParams) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -1956,7 +2091,8 @@ void nsNativeThemeCocoa::DrawScale(CGContextRef cgContext, const HIRect& inBoxRe if (aParams.disabled) { tdi.enableState = kThemeTrackDisabled; } else { - tdi.enableState = aParams.insideActiveWindow ? kThemeTrackActive : kThemeTrackInactive; + tdi.enableState = + aParams.insideActiveWindow ? kThemeTrackActive : kThemeTrackInactive; } tdi.trackInfo.slider.thumbDir = kThemeThumbPlain; tdi.trackInfo.slider.pressState = 0; @@ -1966,7 +2102,8 @@ void nsNativeThemeCocoa::DrawScale(CGContextRef cgContext, const HIRect& inBoxRe NS_OBJC_END_TRY_IGNORE_BLOCK; } -nsIFrame* nsNativeThemeCocoa::SeparatorResponsibility(nsIFrame* aBefore, nsIFrame* aAfter) { +nsIFrame* nsNativeThemeCocoa::SeparatorResponsibility(nsIFrame* aBefore, + nsIFrame* aAfter) { // Usually a separator is drawn by the segment to the right of the // separator, but pressed and selected segments have higher priority. if (!aBefore || !aAfter) return nullptr; @@ -1975,7 +2112,8 @@ nsIFrame* nsNativeThemeCocoa::SeparatorResponsibility(nsIFrame* aBefore, nsIFram return aAfter; } -static CGRect SeparatorAdjustedRect(CGRect aRect, nsNativeThemeCocoa::SegmentParams aParams) { +static CGRect SeparatorAdjustedRect(CGRect aRect, + nsNativeThemeCocoa::SegmentParams aParams) { // A separator between two segments should always be located in the leftmost // pixel column of the segment to the right of the separator, regardless of // who ends up drawing it. @@ -2010,7 +2148,8 @@ struct SegmentedControlRenderSettings { static const CGFloat tabHeights[3] = {17, 20, 23}; -static const SegmentedControlRenderSettings tabRenderSettings = {tabHeights, @"tab"}; +static const SegmentedControlRenderSettings tabRenderSettings = {tabHeights, + @"tab"}; static const CGFloat toolbarButtonHeights[3] = {15, 18, 22}; @@ -2046,22 +2185,30 @@ static SegmentedControlRenderSettings RenderSettingsForSegmentType( } } -void nsNativeThemeCocoa::DrawSegment(CGContextRef cgContext, const HIRect& inBoxRect, +void nsNativeThemeCocoa::DrawSegment(CGContextRef cgContext, + const HIRect& inBoxRect, const SegmentParams& aParams) { - SegmentedControlRenderSettings renderSettings = RenderSettingsForSegmentType(aParams.segmentType); - NSControlSize controlSize = FindControlSize(inBoxRect.size.height, renderSettings.heights, 4.0f); + SegmentedControlRenderSettings renderSettings = + RenderSettingsForSegmentType(aParams.segmentType); + NSControlSize controlSize = + FindControlSize(inBoxRect.size.height, renderSettings.heights, 4.0f); CGRect drawRect = SeparatorAdjustedRect(inBoxRect, aParams); NSDictionary* dict = @{ @"widget" : renderSettings.widgetName, - @"kCUIPresentationStateKey" : (aParams.insideActiveWindow ? @"kCUIPresentationStateActiveKey" - : @"kCUIPresentationStateInactive"), - @"kCUIPositionKey" : ToolbarButtonPosition(aParams.atLeftEnd, aParams.atRightEnd), - @"kCUISegmentLeadingSeparatorKey" : [NSNumber numberWithBool:aParams.drawsLeftSeparator], - @"kCUISegmentTrailingSeparatorKey" : [NSNumber numberWithBool:aParams.drawsRightSeparator], + @"kCUIPresentationStateKey" : + (aParams.insideActiveWindow ? @"kCUIPresentationStateActiveKey" + : @"kCUIPresentationStateInactive"), + @"kCUIPositionKey" : + ToolbarButtonPosition(aParams.atLeftEnd, aParams.atRightEnd), + @"kCUISegmentLeadingSeparatorKey" : + [NSNumber numberWithBool:aParams.drawsLeftSeparator], + @"kCUISegmentTrailingSeparatorKey" : + [NSNumber numberWithBool:aParams.drawsRightSeparator], @"value" : [NSNumber numberWithBool:aParams.selected], - @"state" : - (aParams.pressed ? @"pressed" : (aParams.insideActiveWindow ? @"normal" : @"inactive")), + @"state" : (aParams.pressed + ? @"pressed" + : (aParams.insideActiveWindow ? @"normal" : @"inactive")), @"focus" : [NSNumber numberWithBool:aParams.focused], @"size" : CUIControlSizeForCocoaSize(controlSize), @"is.flipped" : [NSNumber numberWithBool:YES], @@ -2071,8 +2218,8 @@ void nsNativeThemeCocoa::DrawSegment(CGContextRef cgContext, const HIRect& inBox RenderWithCoreUI(drawRect, cgContext, dict); } -void nsNativeThemeCocoa::DrawToolbar(CGContextRef cgContext, const CGRect& inBoxRect, - bool aIsMain) { +void nsNativeThemeCocoa::DrawToolbar(CGContextRef cgContext, + const CGRect& inBoxRect, bool aIsMain) { CGRect drawRect = inBoxRect; // top border @@ -2087,7 +2234,8 @@ void nsNativeThemeCocoa::DrawToolbar(CGContextRef cgContext, const CGRect& inBox // bottom border drawRect.origin.y += drawRect.size.height; drawRect.size.height = 1.0f; - DrawNativeGreyColorInRect(cgContext, toolbarBottomBorderGrey, drawRect, aIsMain); + DrawNativeGreyColorInRect(cgContext, toolbarBottomBorderGrey, drawRect, + aIsMain); } static bool ToolbarCanBeUnified(const gfx::Rect& aRect, NSWindow* aWindow) { @@ -2099,8 +2247,8 @@ static bool ToolbarCanBeUnified(const gfx::Rect& aRect, NSWindow* aWindow) { aRect.YMost() <= unifiedToolbarHeight; } -void nsNativeThemeCocoa::DrawStatusBar(CGContextRef cgContext, const HIRect& inBoxRect, - bool aIsMain) { +void nsNativeThemeCocoa::DrawStatusBar(CGContextRef cgContext, + const HIRect& inBoxRect, bool aIsMain) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; if (inBoxRect.size.height < 2.0f) return; @@ -2117,21 +2265,23 @@ void nsNativeThemeCocoa::DrawStatusBar(CGContextRef cgContext, const HIRect& inB drawRect.size.height += extendUpwards; RenderWithCoreUI( drawRect, cgContext, - [NSDictionary - dictionaryWithObjectsAndKeys:@"kCUIWidgetWindowFrame", @"widget", @"regularwin", - @"windowtype", (aIsMain ? @"normal" : @"inactive"), @"state", - [NSNumber numberWithInt:inBoxRect.size.height], - @"kCUIWindowFrameBottomBarHeightKey", - [NSNumber numberWithBool:YES], - @"kCUIWindowFrameDrawBottomBarSeparatorKey", - [NSNumber numberWithBool:YES], @"is.flipped", nil]); + [NSDictionary dictionaryWithObjectsAndKeys: + @"kCUIWidgetWindowFrame", @"widget", @"regularwin", + @"windowtype", (aIsMain ? @"normal" : @"inactive"), + @"state", + [NSNumber numberWithInt:inBoxRect.size.height], + @"kCUIWindowFrameBottomBarHeightKey", + [NSNumber numberWithBool:YES], + @"kCUIWindowFrameDrawBottomBarSeparatorKey", + [NSNumber numberWithBool:YES], @"is.flipped", nil]); CGContextRestoreGState(cgContext); NS_OBJC_END_TRY_IGNORE_BLOCK; } -void nsNativeThemeCocoa::DrawMultilineTextField(CGContextRef cgContext, const CGRect& inBoxRect, +void nsNativeThemeCocoa::DrawMultilineTextField(CGContextRef cgContext, + const CGRect& inBoxRect, bool aIsFocused) { mTextFieldCell.enabled = YES; mTextFieldCell.showsFirstResponder = aIsFocused; @@ -2140,17 +2290,19 @@ void nsNativeThemeCocoa::DrawMultilineTextField(CGContextRef cgContext, const CG mCellDrawWindow.cellsShouldLookActive = YES; } - // DrawCellIncludingFocusRing draws into the current NSGraphicsContext, so do the usual - // save+restore dance. + // DrawCellIncludingFocusRing draws into the current NSGraphicsContext, so do + // the usual save+restore dance. NSGraphicsContext* savedContext = NSGraphicsContext.currentContext; - NSGraphicsContext.currentContext = [NSGraphicsContext graphicsContextWithCGContext:cgContext - flipped:YES]; + NSGraphicsContext.currentContext = + [NSGraphicsContext graphicsContextWithCGContext:cgContext flipped:YES]; DrawCellIncludingFocusRing(mTextFieldCell, inBoxRect, mCellDrawView); NSGraphicsContext.currentContext = savedContext; } -void nsNativeThemeCocoa::DrawSourceListSelection(CGContextRef aContext, const CGRect& aRect, - bool aWindowIsActive, bool aSelectionIsActive) { +void nsNativeThemeCocoa::DrawSourceListSelection(CGContextRef aContext, + const CGRect& aRect, + bool aWindowIsActive, + bool aSelectionIsActive) { NSColor* fillColor; if (aSelectionIsActive) { // Active selection, blue or graphite. @@ -2168,7 +2320,8 @@ void nsNativeThemeCocoa::DrawSourceListSelection(CGContextRef aContext, const CG } static bool IsHiDPIContext(nsDeviceContext* aContext) { - return AppUnitsPerCSSPixel() >= 2 * aContext->AppUnitsPerDevPixelAtUnitFullZoom(); + return AppUnitsPerCSSPixel() >= + 2 * aContext->AppUnitsPerDevPixelAtUnitFullZoom(); } Maybe nsNativeThemeCocoa::ComputeWidgetInfo( @@ -2200,20 +2353,22 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( return Nothing(); case StyleAppearance::Menuarrow: - return Some( - WidgetInfo::MenuIcon(ComputeMenuIconParams(aFrame, elementState, MenuIcon::eMenuArrow))); + return Some(WidgetInfo::MenuIcon( + ComputeMenuIconParams(aFrame, elementState, MenuIcon::eMenuArrow))); case StyleAppearance::Menuitem: case StyleAppearance::Checkmenuitem: return Some(WidgetInfo::MenuItem(ComputeMenuItemParams( - aFrame, elementState, aAppearance == StyleAppearance::Checkmenuitem))); + aFrame, elementState, + aAppearance == StyleAppearance::Checkmenuitem))); case StyleAppearance::ButtonArrowUp: case StyleAppearance::ButtonArrowDown: { MenuIcon icon = aAppearance == StyleAppearance::ButtonArrowUp ? MenuIcon::eMenuUpScrollArrow : MenuIcon::eMenuDownScrollArrow; - return Some(WidgetInfo::MenuIcon(ComputeMenuIconParams(aFrame, elementState, icon))); + return Some(WidgetInfo::MenuIcon( + ComputeMenuIconParams(aFrame, elementState, icon))); } case StyleAppearance::Tooltip: @@ -2249,13 +2404,17 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( // default buttons in active windows have blue background and white // text, and default buttons in inactive windows have white background // and black text.) - DocumentState docState = aFrame->GetContent()->OwnerDoc()->GetDocumentState(); + DocumentState docState = + aFrame->GetContent()->OwnerDoc()->GetDocumentState(); ControlParams params = ComputeControlParams(aFrame, elementState); - params.insideActiveWindow = !docState.HasState(DocumentState::WINDOW_INACTIVE); - return Some(WidgetInfo::Button(ButtonParams{params, ButtonType::eDefaultPushButton})); + params.insideActiveWindow = + !docState.HasState(DocumentState::WINDOW_INACTIVE); + return Some(WidgetInfo::Button( + ButtonParams{params, ButtonType::eDefaultPushButton})); } if (IsButtonTypeMenu(aFrame)) { - ControlParams controlParams = ComputeControlParams(aFrame, elementState); + ControlParams controlParams = + ComputeControlParams(aFrame, elementState); controlParams.pressed = IsOpenButton(aFrame); DropdownParams params; params.controlParams = controlParams; @@ -2267,26 +2426,31 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( // If the button is tall enough, draw the square button style so that // buttons with non-standard content look good. Otherwise draw normal // rounded aqua buttons. - // This comparison is done based on the height that is calculated without - // the top, because the snapped height can be affected by the top of the - // rect and that may result in different height depending on the top value. - return Some(WidgetInfo::Button(ButtonParams{ComputeControlParams(aFrame, elementState), - ButtonType::eSquareBezelPushButton})); + // This comparison is done based on the height that is calculated + // without the top, because the snapped height can be affected by the + // top of the rect and that may result in different height depending on + // the top value. + return Some(WidgetInfo::Button( + ButtonParams{ComputeControlParams(aFrame, elementState), + ButtonType::eSquareBezelPushButton})); } - return Some(WidgetInfo::Button(ButtonParams{ComputeControlParams(aFrame, elementState), - ButtonType::eRegularPushButton})); + return Some(WidgetInfo::Button( + ButtonParams{ComputeControlParams(aFrame, elementState), + ButtonType::eRegularPushButton})); case StyleAppearance::MozMacHelpButton: return Some(WidgetInfo::Button( - ButtonParams{ComputeControlParams(aFrame, elementState), ButtonType::eHelpButton})); + ButtonParams{ComputeControlParams(aFrame, elementState), + ButtonType::eHelpButton})); case StyleAppearance::MozMacDisclosureButtonOpen: case StyleAppearance::MozMacDisclosureButtonClosed: { - ButtonType buttonType = (aAppearance == StyleAppearance::MozMacDisclosureButtonClosed) - ? ButtonType::eDisclosureButtonClosed - : ButtonType::eDisclosureButtonOpen; - return Some( - WidgetInfo::Button(ButtonParams{ComputeControlParams(aFrame, elementState), buttonType})); + ButtonType buttonType = + (aAppearance == StyleAppearance::MozMacDisclosureButtonClosed) + ? ButtonType::eDisclosureButtonClosed + : ButtonType::eDisclosureButtonOpen; + return Some(WidgetInfo::Button(ButtonParams{ + ComputeControlParams(aFrame, elementState), buttonType})); } case StyleAppearance::Spinner: { @@ -2300,11 +2464,12 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( } SpinButtonParams params; if (content->IsElement()) { - if (content->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::state, u"up"_ns, - eCaseMatters)) { + if (content->AsElement()->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::state, u"up"_ns, eCaseMatters)) { params.pressedButton = Some(SpinButton::eUp); - } else if (content->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::state, - u"down"_ns, eCaseMatters)) { + } else if (content->AsElement()->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::state, u"down"_ns, + eCaseMatters)) { params.pressedButton = Some(SpinButton::eDown); } } @@ -2335,8 +2500,8 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( } break; case StyleAppearance::Toolbarbutton: { - SegmentParams params = - ComputeSegmentParams(aFrame, elementState, SegmentType::eToolbarButton); + SegmentParams params = ComputeSegmentParams(aFrame, elementState, + SegmentType::eToolbarButton); params.insideActiveWindow = [NativeWindowForFrame(aFrame) isMainWindow]; return Some(WidgetInfo::Segment(params)); } @@ -2348,9 +2513,10 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( NSWindow* win = NativeWindowForFrame(aFrame); bool isMain = [win isMainWindow]; if (ToolbarCanBeUnified(nativeWidgetRect, win)) { - // Unified toolbars are drawn similar to vibrancy; we communicate their extents via the - // theme geometry mechanism and then place native views under Gecko's rendering. So Gecko - // just needs to be transparent in the place where the toolbar should be visible. + // Unified toolbars are drawn similar to vibrancy; we communicate their + // extents via the theme geometry mechanism and then place native views + // under Gecko's rendering. So Gecko just needs to be transparent in the + // place where the toolbar should be visible. return Nothing(); } return Some(WidgetInfo::Toolbar(isMain)); @@ -2376,14 +2542,17 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( case StyleAppearance::MozMenulistArrowButton: return Some(WidgetInfo::Button( - ButtonParams{ComputeControlParams(aFrame, elementState), ButtonType::eArrowButton})); + ButtonParams{ComputeControlParams(aFrame, elementState), + ButtonType::eArrowButton})); case StyleAppearance::Textfield: case StyleAppearance::NumberInput: - return Some(WidgetInfo::TextField(ComputeTextFieldParams(aFrame, elementState))); + return Some( + WidgetInfo::TextField(ComputeTextFieldParams(aFrame, elementState))); case StyleAppearance::Searchfield: - return Some(WidgetInfo::SearchField(ComputeTextFieldParams(aFrame, elementState))); + return Some(WidgetInfo::SearchField( + ComputeTextFieldParams(aFrame, elementState))); case StyleAppearance::ProgressBar: { if (elementState.HasState(ElementState::INDETERMINATE)) { @@ -2391,8 +2560,8 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( NS_WARNING("Unable to animate progressbar!"); } } - return Some(WidgetInfo::ProgressBar( - ComputeProgressParams(aFrame, elementState, !IsVerticalProgress(aFrame)))); + return Some(WidgetInfo::ProgressBar(ComputeProgressParams( + aFrame, elementState, !IsVerticalProgress(aFrame)))); } case StyleAppearance::Meter: @@ -2404,15 +2573,18 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( break; case StyleAppearance::Treetwisty: - return Some(WidgetInfo::Button(ButtonParams{ComputeControlParams(aFrame, elementState), - ButtonType::eTreeTwistyPointingRight})); + return Some(WidgetInfo::Button( + ButtonParams{ComputeControlParams(aFrame, elementState), + ButtonType::eTreeTwistyPointingRight})); case StyleAppearance::Treetwistyopen: - return Some(WidgetInfo::Button(ButtonParams{ComputeControlParams(aFrame, elementState), - ButtonType::eTreeTwistyPointingDown})); + return Some(WidgetInfo::Button( + ButtonParams{ComputeControlParams(aFrame, elementState), + ButtonType::eTreeTwistyPointingDown})); case StyleAppearance::Treeheadercell: - return Some(WidgetInfo::TreeHeaderCell(ComputeTreeHeaderCellParams(aFrame, elementState))); + return Some(WidgetInfo::TreeHeaderCell( + ComputeTreeHeaderCellParams(aFrame, elementState))); case StyleAppearance::Treeitem: case StyleAppearance::Treeview: @@ -2435,7 +2607,8 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( } case StyleAppearance::Textarea: - return Some(WidgetInfo::MultilineTextField(elementState.HasState(ElementState::FOCUS))); + return Some(WidgetInfo::MultilineTextField( + elementState.HasState(ElementState::FOCUS))); case StyleAppearance::Listbox: return Some(WidgetInfo::ListBox()); @@ -2459,7 +2632,8 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( } case StyleAppearance::Tab: { - SegmentParams params = ComputeSegmentParams(aFrame, elementState, SegmentType::eTab); + SegmentParams params = + ComputeSegmentParams(aFrame, elementState, SegmentType::eTab); params.pressed = params.pressed && !params.selected; return Some(WidgetInfo::Segment(params)); } @@ -2478,13 +2652,15 @@ Maybe nsNativeThemeCocoa::ComputeWidgetInfo( NS_IMETHODIMP nsNativeThemeCocoa::DrawWidgetBackground(gfxContext* aContext, nsIFrame* aFrame, - StyleAppearance aAppearance, const nsRect& aRect, - const nsRect& aDirtyRect, DrawOverflow aDrawOverflow) { + StyleAppearance aAppearance, + const nsRect& aRect, + const nsRect& aDirtyRect, + DrawOverflow aDrawOverflow) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; if (IsWidgetAlwaysNonNative(aFrame, aAppearance)) { - return ThemeCocoa::DrawWidgetBackground(aContext, aFrame, aAppearance, aRect, aDirtyRect, - aDrawOverflow); + return ThemeCocoa::DrawWidgetBackground(aContext, aFrame, aAppearance, + aRect, aDirtyRect, aDrawOverflow); } Maybe widgetInfo = ComputeWidgetInfo(aFrame, aAppearance, aRect); @@ -2502,8 +2678,9 @@ nsNativeThemeCocoa::DrawWidgetBackground(gfxContext* aContext, nsIFrame* aFrame, auto colorScheme = LookAndFeel::ColorSchemeForFrame(aFrame); - RenderWidget(*widgetInfo, colorScheme, *aContext->GetDrawTarget(), nativeWidgetRect, - NSRectToRect(aDirtyRect, p2a), hidpi ? 2.0f : 1.0f); + RenderWidget(*widgetInfo, colorScheme, *aContext->GetDrawTarget(), + nativeWidgetRect, NSRectToRect(aDirtyRect, p2a), + hidpi ? 2.0f : 1.0f); return NS_OK; @@ -2511,15 +2688,18 @@ nsNativeThemeCocoa::DrawWidgetBackground(gfxContext* aContext, nsIFrame* aFrame, } void nsNativeThemeCocoa::RenderWidget(const WidgetInfo& aWidgetInfo, - LookAndFeel::ColorScheme aScheme, DrawTarget& aDrawTarget, - const gfx::Rect& aWidgetRect, const gfx::Rect& aDirtyRect, + LookAndFeel::ColorScheme aScheme, + DrawTarget& aDrawTarget, + const gfx::Rect& aWidgetRect, + const gfx::Rect& aDirtyRect, float aScale) { - // Some of the drawing below uses NSAppearance.currentAppearance behind the scenes. - // Set it to the appearance we want, the same way as nsLookAndFeel::NativeGetColor. + // Some of the drawing below uses NSAppearance.currentAppearance behind the + // scenes. Set it to the appearance we want, the same way as + // nsLookAndFeel::NativeGetColor. NSAppearance.currentAppearance = NSAppearanceForColorScheme(aScheme); - // Also set the cell draw window's appearance; this is respected by NSTextFieldCell (and its - // subclass NSSearchFieldCell). + // Also set the cell draw window's appearance; this is respected by + // NSTextFieldCell (and its subclass NSSearchFieldCell). if (mCellDrawWindow) { mCellDrawWindow.appearance = NSAppearance.currentAppearance; } @@ -2540,11 +2720,12 @@ void nsNativeThemeCocoa::RenderWidget(const WidgetInfo& aWidgetInfo, dirtyRect.Scale(1.0f / aScale); widgetRect.Scale(1.0f / aScale); - aDrawTarget.SetTransform(aDrawTarget.GetTransform().PreScale(aScale, aScale)); + aDrawTarget.SetTransform( + aDrawTarget.GetTransform().PreScale(aScale, aScale)); // The remaining widgets require a CGContext. - CGRect macRect = - CGRectMake(widgetRect.X(), widgetRect.Y(), widgetRect.Width(), widgetRect.Height()); + CGRect macRect = CGRectMake(widgetRect.X(), widgetRect.Y(), + widgetRect.Width(), widgetRect.Height()); gfxQuartzNativeDrawing nativeDrawing(aDrawTarget, dirtyRect); @@ -2557,8 +2738,10 @@ void nsNativeThemeCocoa::RenderWidget(const WidgetInfo& aWidgetInfo, return; } - // Set the context's "base transform" to in order to get correctly-sized focus rings. - CGContextSetBaseCTM(cgContext, CGAffineTransformMakeScale(aScale, aScale)); + // Set the context's "base transform" to in order to get correctly-sized + // focus rings. + CGContextSetBaseCTM(cgContext, + CGAffineTransformMakeScale(aScale, aScale)); switch (widget) { case Widget::eColorFill: @@ -2575,12 +2758,14 @@ void nsNativeThemeCocoa::RenderWidget(const WidgetInfo& aWidgetInfo, break; } case Widget::eCheckbox: { - CheckboxOrRadioParams params = aWidgetInfo.Params(); + CheckboxOrRadioParams params = + aWidgetInfo.Params(); DrawCheckboxOrRadio(cgContext, true, macRect, params); break; } case Widget::eRadio: { - CheckboxOrRadioParams params = aWidgetInfo.Params(); + CheckboxOrRadioParams params = + aWidgetInfo.Params(); DrawCheckboxOrRadio(cgContext, false, macRect, params); break; } @@ -2630,7 +2815,8 @@ void nsNativeThemeCocoa::RenderWidget(const WidgetInfo& aWidgetInfo, break; } case Widget::eGroupBox: { - HIThemeGroupBoxDrawInfo gdi = {0, kThemeStateActive, kHIThemeGroupBoxKindPrimary}; + HIThemeGroupBoxDrawInfo gdi = {0, kThemeStateActive, + kHIThemeGroupBoxKindPrimary}; HIThemeDrawGroupBox(&macRect, &gdi, cgContext, HITHEME_ORIENTATION); break; } @@ -2655,7 +2841,8 @@ void nsNativeThemeCocoa::RenderWidget(const WidgetInfo& aWidgetInfo, break; } case Widget::eTreeHeaderCell: { - TreeHeaderCellParams params = aWidgetInfo.Params(); + TreeHeaderCellParams params = + aWidgetInfo.Params(); DrawTreeHeaderCell(cgContext, macRect, params); break; } @@ -2671,10 +2858,13 @@ void nsNativeThemeCocoa::RenderWidget(const WidgetInfo& aWidgetInfo, } case Widget::eListBox: { // Fill the content with the control background color. - CGContextSetFillColorWithColor(cgContext, [NSColor.controlBackgroundColor CGColor]); + CGContextSetFillColorWithColor( + cgContext, [NSColor.controlBackgroundColor CGColor]); CGContextFillRect(cgContext, macRect); - // Draw the frame using kCUIWidgetScrollViewFrame. This is what NSScrollView uses in - // -[NSScrollView drawRect:] if you give it a borderType of NSBezelBorder. + // Draw the frame using kCUIWidgetScrollViewFrame. This is what + // NSScrollView uses in + // -[NSScrollView drawRect:] if you give it a borderType of + // NSBezelBorder. RenderWithCoreUI( macRect, cgContext, @{ @"widget" : @"kCUIWidgetScrollViewFrame", @@ -2686,8 +2876,10 @@ void nsNativeThemeCocoa::RenderWidget(const WidgetInfo& aWidgetInfo, case Widget::eActiveSourceListSelection: case Widget::eInactiveSourceListSelection: { bool isInActiveWindow = aWidgetInfo.Params(); - bool isActiveSelection = aWidgetInfo.Widget() == Widget::eActiveSourceListSelection; - DrawSourceListSelection(cgContext, macRect, isInActiveWindow, isActiveSelection); + bool isActiveSelection = + aWidgetInfo.Widget() == Widget::eActiveSourceListSelection; + DrawSourceListSelection(cgContext, macRect, isInActiveWindow, + isActiveSelection); break; } case Widget::eTabPanel: { @@ -2706,13 +2898,14 @@ void nsNativeThemeCocoa::RenderWidget(const WidgetInfo& aWidgetInfo, } bool nsNativeThemeCocoa::CreateWebRenderCommandsForWidget( - mozilla::wr::DisplayListBuilder& aBuilder, mozilla::wr::IpcResourceUpdateQueue& aResources, + mozilla::wr::DisplayListBuilder& aBuilder, + mozilla::wr::IpcResourceUpdateQueue& aResources, const mozilla::layers::StackingContextHelper& aSc, mozilla::layers::RenderRootStateManager* aManager, nsIFrame* aFrame, StyleAppearance aAppearance, const nsRect& aRect) { if (IsWidgetAlwaysNonNative(aFrame, aAppearance)) { - return ThemeCocoa::CreateWebRenderCommandsForWidget(aBuilder, aResources, aSc, aManager, aFrame, - aAppearance, aRect); + return ThemeCocoa::CreateWebRenderCommandsForWidget( + aBuilder, aResources, aSc, aManager, aFrame, aAppearance, aRect); } // This list needs to stay consistent with the list in DrawWidgetBackground. @@ -2771,13 +2964,14 @@ bool nsNativeThemeCocoa::CreateWebRenderCommandsForWidget( } } -LayoutDeviceIntMargin nsNativeThemeCocoa::DirectionAwareMargin(const LayoutDeviceIntMargin& aMargin, - nsIFrame* aFrame) { +LayoutDeviceIntMargin nsNativeThemeCocoa::DirectionAwareMargin( + const LayoutDeviceIntMargin& aMargin, nsIFrame* aFrame) { // Assuming aMargin was originally specified for a horizontal LTR context, // reinterpret the values as logical, and then map to physical coords // according to aFrame's actual writing mode. WritingMode wm = aFrame->GetWritingMode(); - nsMargin m = LogicalMargin(wm, aMargin.top, aMargin.right, aMargin.bottom, aMargin.left) + nsMargin m = LogicalMargin(wm, aMargin.top, aMargin.right, aMargin.bottom, + aMargin.left) .GetPhysicalMargin(wm); return LayoutDeviceIntMargin(m.top, m.right, m.bottom, m.left); } @@ -2787,9 +2981,8 @@ static const LayoutDeviceIntMargin kAquaComboboxBorder(3, 20, 3, 4); static const LayoutDeviceIntMargin kAquaSearchfieldBorder(3, 5, 2, 19); static const LayoutDeviceIntMargin kAquaSearchfieldBorderBigSur(5, 5, 4, 26); -LayoutDeviceIntMargin nsNativeThemeCocoa::GetWidgetBorder(nsDeviceContext* aContext, - nsIFrame* aFrame, - StyleAppearance aAppearance) { +LayoutDeviceIntMargin nsNativeThemeCocoa::GetWidgetBorder( + nsDeviceContext* aContext, nsIFrame* aFrame, StyleAppearance aAppearance) { if (IsWidgetAlwaysNonNative(aFrame, aAppearance)) { return Theme::GetWidgetBorder(aContext, aFrame, aAppearance); } @@ -2802,7 +2995,8 @@ LayoutDeviceIntMargin nsNativeThemeCocoa::GetWidgetBorder(nsDeviceContext* aCont if (IsButtonTypeMenu(aFrame)) { result = DirectionAwareMargin(kAquaDropdownBorder, aFrame); } else { - result = DirectionAwareMargin(LayoutDeviceIntMargin(1, 7, 3, 7), aFrame); + result = + DirectionAwareMargin(LayoutDeviceIntMargin(1, 7, 3, 7), aFrame); } break; } @@ -2814,8 +3008,8 @@ LayoutDeviceIntMargin nsNativeThemeCocoa::GetWidgetBorder(nsDeviceContext* aCont case StyleAppearance::Checkbox: case StyleAppearance::Radio: { - // nsCheckboxRadioFrame::GetIntrinsicWidth and nsCheckboxRadioFrame::GetIntrinsicHeight - // assume a border width of 2px. + // nsCheckboxRadioFrame::GetIntrinsicWidth and + // nsCheckboxRadioFrame::GetIntrinsicHeight assume a border width of 2px. result.SizeTo(2, 2, 2, 2); break; } @@ -2851,8 +3045,9 @@ LayoutDeviceIntMargin nsNativeThemeCocoa::GetWidgetBorder(nsDeviceContext* aCont break; case StyleAppearance::Searchfield: { - auto border = nsCocoaFeatures::OnBigSurOrLater() ? kAquaSearchfieldBorderBigSur - : kAquaSearchfieldBorder; + auto border = nsCocoaFeatures::OnBigSurOrLater() + ? kAquaSearchfieldBorderBigSur + : kAquaSearchfieldBorder; result = DirectionAwareMargin(border, aFrame); break; } @@ -2879,11 +3074,12 @@ LayoutDeviceIntMargin nsNativeThemeCocoa::GetWidgetBorder(nsDeviceContext* aCont NS_OBJC_END_TRY_BLOCK_RETURN(result); } -// Return false here to indicate that CSS padding values should be used. There is -// no reason to make a distinction between padding and border values, just specify -// whatever values you want in GetWidgetBorder and only use this to return true -// if you want to override CSS padding values. -bool nsNativeThemeCocoa::GetWidgetPadding(nsDeviceContext* aContext, nsIFrame* aFrame, +// Return false here to indicate that CSS padding values should be used. There +// is no reason to make a distinction between padding and border values, just +// specify whatever values you want in GetWidgetBorder and only use this to +// return true if you want to override CSS padding values. +bool nsNativeThemeCocoa::GetWidgetPadding(nsDeviceContext* aContext, + nsIFrame* aFrame, StyleAppearance aAppearance, LayoutDeviceIntMargin* aResult) { if (IsWidgetAlwaysNonNative(aFrame, aAppearance)) { @@ -2914,10 +3110,13 @@ bool nsNativeThemeCocoa::GetWidgetPadding(nsDeviceContext* aContext, nsIFrame* a return false; } -bool nsNativeThemeCocoa::GetWidgetOverflow(nsDeviceContext* aContext, nsIFrame* aFrame, - StyleAppearance aAppearance, nsRect* aOverflowRect) { +bool nsNativeThemeCocoa::GetWidgetOverflow(nsDeviceContext* aContext, + nsIFrame* aFrame, + StyleAppearance aAppearance, + nsRect* aOverflowRect) { if (IsWidgetAlwaysNonNative(aFrame, aAppearance)) { - return ThemeCocoa::GetWidgetOverflow(aContext, aFrame, aAppearance, aOverflowRect); + return ThemeCocoa::GetWidgetOverflow(aContext, aFrame, aAppearance, + aOverflowRect); } nsIntMargin overflow; switch (aAppearance) { @@ -2937,13 +3136,15 @@ bool nsNativeThemeCocoa::GetWidgetOverflow(nsDeviceContext* aContext, nsIFrame* case StyleAppearance::Checkbox: case StyleAppearance::Radio: case StyleAppearance::Tab: { - overflow.SizeTo( - static_cast(kMaxFocusRingWidth), static_cast(kMaxFocusRingWidth), - static_cast(kMaxFocusRingWidth), static_cast(kMaxFocusRingWidth)); + overflow.SizeTo(static_cast(kMaxFocusRingWidth), + static_cast(kMaxFocusRingWidth), + static_cast(kMaxFocusRingWidth), + static_cast(kMaxFocusRingWidth)); break; } case StyleAppearance::ProgressBar: { - // Progress bars draw a 2 pixel white shadow under their progress indicators. + // Progress bars draw a 2 pixel white shadow under their progress + // indicators. overflow.bottom = 2; break; } @@ -2963,18 +3164,19 @@ bool nsNativeThemeCocoa::GetWidgetOverflow(nsDeviceContext* aContext, nsIFrame* if (overflow != nsIntMargin()) { int32_t p2a = aFrame->PresContext()->AppUnitsPerDevPixel(); - aOverflowRect->Inflate(nsMargin( - NSIntPixelsToAppUnits(overflow.top, p2a), NSIntPixelsToAppUnits(overflow.right, p2a), - NSIntPixelsToAppUnits(overflow.bottom, p2a), NSIntPixelsToAppUnits(overflow.left, p2a))); + aOverflowRect->Inflate(nsMargin(NSIntPixelsToAppUnits(overflow.top, p2a), + NSIntPixelsToAppUnits(overflow.right, p2a), + NSIntPixelsToAppUnits(overflow.bottom, p2a), + NSIntPixelsToAppUnits(overflow.left, p2a))); return true; } return false; } -LayoutDeviceIntSize nsNativeThemeCocoa::GetMinimumWidgetSize(nsPresContext* aPresContext, - nsIFrame* aFrame, - StyleAppearance aAppearance) { +LayoutDeviceIntSize nsNativeThemeCocoa::GetMinimumWidgetSize( + nsPresContext* aPresContext, nsIFrame* aFrame, + StyleAppearance aAppearance) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; if (IsWidgetAlwaysNonNative(aFrame, aAppearance)) { @@ -3024,7 +3226,9 @@ LayoutDeviceIntSize nsNativeThemeCocoa::GetMinimumWidgetSize(nsPresContext* aPre ::GetThemeMetric(kThemeMetricLittleArrowsWidth, &buttonWidth); ::GetThemeMetric(kThemeMetricLittleArrowsHeight, &buttonHeight); } else { - NSSize size = spinnerSettings.minimumSizes[EnumSizeForCocoaSize(NSControlSizeMini)]; + NSSize size = + spinnerSettings + .minimumSizes[EnumSizeForCocoaSize(NSControlSizeMini)]; buttonWidth = size.width; buttonHeight = size.height; if (aAppearance != StyleAppearance::Spinner) { @@ -3105,7 +3309,8 @@ LayoutDeviceIntSize nsNativeThemeCocoa::GetMinimumWidgetSize(nsPresContext* aPre } case StyleAppearance::MozMenulistArrowButton: - return ThemeCocoa::GetMinimumWidgetSize(aPresContext, aFrame, aAppearance); + return ThemeCocoa::GetMinimumWidgetSize(aPresContext, aFrame, + aAppearance); default: break; @@ -3121,7 +3326,8 @@ LayoutDeviceIntSize nsNativeThemeCocoa::GetMinimumWidgetSize(nsPresContext* aPre } NS_IMETHODIMP -nsNativeThemeCocoa::WidgetStateChanged(nsIFrame* aFrame, StyleAppearance aAppearance, +nsNativeThemeCocoa::WidgetStateChanged(nsIFrame* aFrame, + StyleAppearance aAppearance, nsAtom* aAttribute, bool* aShouldRepaint, const nsAttrValue* aOldValue) { // Some widget types just never change state. @@ -3156,8 +3362,10 @@ nsNativeThemeCocoa::WidgetStateChanged(nsIFrame* aFrame, StyleAppearance aAppear // disabled, checked, dlgtype, default, etc. *aShouldRepaint = false; if (aAttribute == nsGkAtoms::disabled || aAttribute == nsGkAtoms::checked || - aAttribute == nsGkAtoms::selected || aAttribute == nsGkAtoms::visuallyselected || - aAttribute == nsGkAtoms::menuactive || aAttribute == nsGkAtoms::sortDirection || + aAttribute == nsGkAtoms::selected || + aAttribute == nsGkAtoms::visuallyselected || + aAttribute == nsGkAtoms::menuactive || + aAttribute == nsGkAtoms::sortDirection || aAttribute == nsGkAtoms::focused || aAttribute == nsGkAtoms::_default || aAttribute == nsGkAtoms::open || aAttribute == nsGkAtoms::hover) *aShouldRepaint = true; @@ -3174,7 +3382,8 @@ nsNativeThemeCocoa::ThemeChanged() { return NS_OK; } -bool nsNativeThemeCocoa::ThemeSupportsWidget(nsPresContext* aPresContext, nsIFrame* aFrame, +bool nsNativeThemeCocoa::ThemeSupportsWidget(nsPresContext* aPresContext, + nsIFrame* aFrame, StyleAppearance aAppearance) { if (IsWidgetAlwaysNonNative(aFrame, aAppearance)) { return ThemeCocoa::ThemeSupportsWidget(aPresContext, aFrame, aAppearance); @@ -3275,7 +3484,8 @@ bool nsNativeThemeCocoa::WidgetIsContainer(StyleAppearance aAppearance) { return true; } -bool nsNativeThemeCocoa::ThemeDrawsFocusForWidget(nsIFrame*, StyleAppearance aAppearance) { +bool nsNativeThemeCocoa::ThemeDrawsFocusForWidget(nsIFrame*, + StyleAppearance aAppearance) { switch (aAppearance) { case StyleAppearance::Textarea: case StyleAppearance::Textfield: @@ -3298,7 +3508,8 @@ bool nsNativeThemeCocoa::ThemeDrawsFocusForWidget(nsIFrame*, StyleAppearance aAp bool nsNativeThemeCocoa::ThemeNeedsComboboxDropmarker() { return false; } -bool nsNativeThemeCocoa::WidgetAppearanceDependsOnWindowFocus(StyleAppearance aAppearance) { +bool nsNativeThemeCocoa::WidgetAppearanceDependsOnWindowFocus( + StyleAppearance aAppearance) { switch (aAppearance) { case StyleAppearance::Dialog: case StyleAppearance::Tabpanels: @@ -3345,8 +3556,10 @@ nsITheme::ThemeGeometryType nsNativeThemeCocoa::ThemeGeometryTypeForWidget( case StyleAppearance::Checkmenuitem: { ElementState elementState = GetContentState(aFrame, aAppearance); bool isDisabled = elementState.HasState(ElementState::DISABLED); - bool isSelected = !isDisabled && CheckBooleanAttr(aFrame, nsGkAtoms::menuactive); - return isSelected ? eThemeGeometryTypeHighlightedMenuItem : eThemeGeometryTypeMenu; + bool isSelected = + !isDisabled && CheckBooleanAttr(aFrame, nsGkAtoms::menuactive); + return isSelected ? eThemeGeometryTypeHighlightedMenuItem + : eThemeGeometryTypeMenu; } case StyleAppearance::MozMacSourceList: return eThemeGeometryTypeSourceList; @@ -3354,15 +3567,16 @@ nsITheme::ThemeGeometryType nsNativeThemeCocoa::ThemeGeometryTypeForWidget( return IsInSourceList(aFrame) ? eThemeGeometryTypeSourceListSelection : eThemeGeometryTypeUnknown; case StyleAppearance::MozMacActiveSourceListSelection: - return IsInSourceList(aFrame) ? eThemeGeometryTypeActiveSourceListSelection - : eThemeGeometryTypeUnknown; + return IsInSourceList(aFrame) + ? eThemeGeometryTypeActiveSourceListSelection + : eThemeGeometryTypeUnknown; default: return eThemeGeometryTypeUnknown; } } -nsITheme::Transparency nsNativeThemeCocoa::GetWidgetTransparency(nsIFrame* aFrame, - StyleAppearance aAppearance) { +nsITheme::Transparency nsNativeThemeCocoa::GetWidgetTransparency( + nsIFrame* aFrame, StyleAppearance aAppearance) { if (IsWidgetScrollbarPart(aAppearance)) { return ThemeCocoa::GetWidgetTransparency(aFrame, aAppearance); } diff --git a/widget/cocoa/nsPrintDialogX.mm b/widget/cocoa/nsPrintDialogX.mm index 9a087912a677..01d62d8ab7bb 100644 --- a/widget/cocoa/nsPrintDialogX.mm +++ b/widget/cocoa/nsPrintDialogX.mm @@ -73,7 +73,8 @@ NS_IMETHODIMP nsPrintDialogServiceX::Init() { return NS_OK; } NS_IMETHODIMP -nsPrintDialogServiceX::ShowPrintDialog(mozIDOMWindowProxy* aParent, bool aHaveSelection, +nsPrintDialogServiceX::ShowPrintDialog(mozIDOMWindowProxy* aParent, + bool aHaveSelection, nsIPrintSettings* aSettings) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; @@ -84,7 +85,8 @@ nsPrintDialogServiceX::ShowPrintDialog(mozIDOMWindowProxy* aParent, bool aHaveSe return NS_ERROR_FAILURE; } - NSPrintInfo* printInfo = settingsX->CreateOrCopyPrintInfo(/* aWithScaling = */ true); + NSPrintInfo* printInfo = + settingsX->CreateOrCopyPrintInfo(/* aWithScaling = */ true); if (NS_WARN_IF(!printInfo)) { return NS_ERROR_FAILURE; } @@ -100,7 +102,8 @@ nsPrintDialogServiceX::ShowPrintDialog(mozIDOMWindowProxy* aParent, bool aHaveSe NULL, reinterpret_cast(adjustedTitle.BeginReading()), adjustedTitle.Length()); if (cfTitleString) { - auto pmPrintSettings = static_cast([printInfo PMPrintSettings]); + auto pmPrintSettings = + static_cast([printInfo PMPrintSettings]); ::PMPrintSettingsSetJobName(pmPrintSettings, cfTitleString); [printInfo updateFromPMPrintSettings]; CFRelease(cfTitleString); @@ -117,8 +120,8 @@ nsPrintDialogServiceX::ShowPrintDialog(mozIDOMWindowProxy* aParent, bool aHaveSe // [panel runModal] will look for it. We create the view because otherwise // we'll get unrelated warnings printed to the console. NSView* tmpView = [[NSView alloc] init]; - NSPrintOperation* printOperation = [NSPrintOperation printOperationWithView:tmpView - printInfo:printInfo]; + NSPrintOperation* printOperation = + [NSPrintOperation printOperationWithView:tmpView printInfo:printInfo]; [NSPrintOperation setCurrentOperation:printOperation]; NSPrintPanel* panel = [NSPrintPanel printPanel]; @@ -136,8 +139,9 @@ nsPrintDialogServiceX::ShowPrintDialog(mozIDOMWindowProxy* aParent, bool aHaveSe int button = [panel runModal]; nsCocoaUtils::CleanUpAfterNativeAppModalDialog(); - // Retrieve a printInfo with the updated settings. (The NSPrintOperation operates on a - // copy, so the object we passed in will not have been modified.) + // Retrieve a printInfo with the updated settings. (The NSPrintOperation + // operates on a copy, so the object we passed in will not have been + // modified.) NSPrintInfo* result = [[NSPrintOperation currentOperation] printInfo]; if (!result) { return NS_ERROR_FAILURE; @@ -164,9 +168,9 @@ nsPrintDialogServiceX::ShowPrintDialog(mozIDOMWindowProxy* aParent, bool aHaveSe [viewController exportSettings]; // Update our settings object based on the user's choices in the dialog. - // We tell settingsX to adopt this printInfo so that it will be used to run print job, - // so that any printer-specific custom settings from print dialog extension panels - // will be carried through. + // We tell settingsX to adopt this printInfo so that it will be used to run + // print job, so that any printer-specific custom settings from print dialog + // extension panels will be carried through. settingsX->SetFromPrintInfo(result, /* aAdoptPrintInfo = */ true); return NS_OK; @@ -188,7 +192,8 @@ nsPrintDialogServiceX::ShowPageSetupDialog(mozIDOMWindowProxy* aParent, return NS_ERROR_FAILURE; } - NSPrintInfo* printInfo = settingsX->CreateOrCopyPrintInfo(/* aWithScaling = */ true); + NSPrintInfo* printInfo = + settingsX->CreateOrCopyPrintInfo(/* aWithScaling = */ true); if (NS_WARN_IF(!printInfo)) { return NS_ERROR_FAILURE; } @@ -200,15 +205,17 @@ nsPrintDialogServiceX::ShowPageSetupDialog(mozIDOMWindowProxy* aParent, nsCocoaUtils::CleanUpAfterNativeAppModalDialog(); if (button == NSFileHandlingPanelOKButton) { - // The Page Setup dialog does not include non-standard settings that need to be preserved, - // separate from what the base printSettings object handles, so we do not need it to adopt - // the printInfo object here. + // The Page Setup dialog does not include non-standard settings that need to + // be preserved, separate from what the base printSettings object handles, + // so we do not need it to adopt the printInfo object here. settingsX->SetFromPrintInfo(printInfo, /* aAdoptPrintInfo = */ false); nsCOMPtr printSettingsService = do_GetService("@mozilla.org/gfx/printsettings-service;1"); - if (printSettingsService && Preferences::GetBool("print.save_print_settings", false)) { + if (printSettingsService && + Preferences::GetBool("print.save_print_settings", false)) { uint32_t flags = nsIPrintSettings::kInitSavePaperSize | - nsIPrintSettings::kInitSaveOrientation | nsIPrintSettings::kInitSaveScaling; + nsIPrintSettings::kInitSaveOrientation | + nsIPrintSettings::kInitSaveScaling; printSettingsService->MaybeSavePrintSettingsToPrefs(aNSSettings, flags); } return NS_OK; @@ -234,7 +241,9 @@ nsPrintDialogServiceX::ShowPageSetupDialog(mozIDOMWindowProxy* aParent, withFrame:(NSRect)aRect alignment:(NSTextAlignment)aAlignment; -- (void)addLabel:(const char*)aLabel withFrame:(NSRect)aRect alignment:(NSTextAlignment)aAlignment; +- (void)addLabel:(const char*)aLabel + withFrame:(NSRect)aRect + alignment:(NSTextAlignment)aAlignment; - (void)addLabel:(const char*)aLabel withFrame:(NSRect)aRect; @@ -243,7 +252,8 @@ nsPrintDialogServiceX::ShowPageSetupDialog(mozIDOMWindowProxy* aParent, - (NSButton*)checkboxWithLabel:(const char*)aLabel andFrame:(NSRect)aRect; - (NSPopUpButton*)headerFooterItemListWithFrame:(NSRect)aRect - selectedItem:(const nsAString&)aCurrentString; + selectedItem: + (const nsAString&)aCurrentString; - (void)addOptionsSection:(bool)aHaveSelection; @@ -265,7 +275,8 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; // Public methods -- (id)initWithSettings:(nsIPrintSettings*)aSettings haveSelection:(bool)aHaveSelection { +- (id)initWithSettings:(nsIPrintSettings*)aSettings + haveSelection:(bool)aHaveSelection { [super initWithFrame:NSMakeRect(0, 0, 540, 185)]; mSettings = aSettings; @@ -278,7 +289,8 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; } - (void)exportSettings { - mSettings->SetPrintSelectionOnly([mPrintSelectionOnlyCheckbox state] == NSOnState); + mSettings->SetPrintSelectionOnly([mPrintSelectionOnlyCheckbox state] == + NSOnState); mSettings->SetShrinkToFit([mShrinkToFitCheckbox state] == NSOnState); mSettings->SetPrintBGColors([mPrintBGColorsCheckbox state] == NSOnState); mSettings->SetPrintBGImages([mPrintBGImagesCheckbox state] == NSOnState); @@ -294,8 +306,10 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; // Localization - (void)initBundle { - nsCOMPtr bundleSvc = do_GetService(NS_STRINGBUNDLE_CONTRACTID); - bundleSvc->CreateBundle("chrome://global/locale/printdialog.properties", &mPrintBundle); + nsCOMPtr bundleSvc = + do_GetService(NS_STRINGBUNDLE_CONTRACTID); + bundleSvc->CreateBundle("chrome://global/locale/printdialog.properties", + &mPrintBundle); } - (NSString*)localizedString:(const char*)aKey { @@ -303,11 +317,14 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; nsAutoString intlString; mPrintBundle->GetStringFromName(aKey, intlString); - NSMutableString* s = - [NSMutableString stringWithUTF8String:NS_ConvertUTF16toUTF8(intlString).get()]; + NSMutableString* s = [NSMutableString + stringWithUTF8String:NS_ConvertUTF16toUTF8(intlString).get()]; // Remove all underscores (they're used in the GTK dialog for accesskeys). - [s replaceOccurrencesOfString:@"_" withString:@"" options:0 range:NSMakeRange(0, [s length])]; + [s replaceOccurrencesOfString:@"_" + withString:@"" + options:0 + range:NSMakeRange(0, [s length])]; return s; } @@ -328,7 +345,9 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; return label; } -- (void)addLabel:(const char*)aLabel withFrame:(NSRect)aRect alignment:(NSTextAlignment)aAlignment { +- (void)addLabel:(const char*)aLabel + withFrame:(NSRect)aRect + alignment:(NSTextAlignment)aAlignment { NSTextField* label = [self label:aLabel withFrame:aRect alignment:aAlignment]; [self addSubview:label]; } @@ -352,16 +371,19 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; } - (NSPopUpButton*)headerFooterItemListWithFrame:(NSRect)aRect - selectedItem:(const nsAString&)aCurrentString { - NSPopUpButton* list = [[[NSPopUpButton alloc] initWithFrame:aRect pullsDown:NO] autorelease]; + selectedItem: + (const nsAString&)aCurrentString { + NSPopUpButton* list = [[[NSPopUpButton alloc] initWithFrame:aRect + pullsDown:NO] autorelease]; [list setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]]; [[list cell] setControlSize:NSControlSizeSmall]; - NSArray* items = [NSArray arrayWithObjects:[self localizedString:"headerFooterBlank"], - [self localizedString:"headerFooterTitle"], - [self localizedString:"headerFooterURL"], - [self localizedString:"headerFooterDate"], - [self localizedString:"headerFooterPage"], - [self localizedString:"headerFooterPageTotal"], nil]; + NSArray* items = [NSArray + arrayWithObjects:[self localizedString:"headerFooterBlank"], + [self localizedString:"headerFooterTitle"], + [self localizedString:"headerFooterURL"], + [self localizedString:"headerFooterDate"], + [self localizedString:"headerFooterPage"], + [self localizedString:"headerFooterPageTotal"], nil]; [list addItemsWithTitles:items]; NS_ConvertUTF16toUTF8 currentStringUTF8(aCurrentString); @@ -382,8 +404,9 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; [self addLabel:"optionsTitleMac" withFrame:NSMakeRect(0, 155, 151, 22)]; // "Print Selection Only" - mPrintSelectionOnlyCheckbox = [self checkboxWithLabel:"selectionOnly" - andFrame:NSMakeRect(156, 155, 0, 0)]; + mPrintSelectionOnlyCheckbox = + [self checkboxWithLabel:"selectionOnly" + andFrame:NSMakeRect(156, 155, 0, 0)]; [mPrintSelectionOnlyCheckbox setEnabled:aHaveSelection]; if (mSettings->GetPrintSelectionOnly()) { @@ -393,7 +416,8 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; [self addSubview:mPrintSelectionOnlyCheckbox]; // "Shrink To Fit" - mShrinkToFitCheckbox = [self checkboxWithLabel:"shrinkToFit" andFrame:NSMakeRect(156, 133, 0, 0)]; + mShrinkToFitCheckbox = [self checkboxWithLabel:"shrinkToFit" + andFrame:NSMakeRect(156, 133, 0, 0)]; bool shrinkToFit; mSettings->GetShrinkToFit(&shrinkToFit); @@ -437,33 +461,39 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; nsString sel; mSettings->GetHeaderStrLeft(sel); - mHeaderLeftList = [self headerFooterItemListWithFrame:NSMakeRect(156, 44, 100, 22) - selectedItem:sel]; + mHeaderLeftList = + [self headerFooterItemListWithFrame:NSMakeRect(156, 44, 100, 22) + selectedItem:sel]; [self addSubview:mHeaderLeftList]; mSettings->GetHeaderStrCenter(sel); - mHeaderCenterList = [self headerFooterItemListWithFrame:NSMakeRect(256, 44, 100, 22) - selectedItem:sel]; + mHeaderCenterList = + [self headerFooterItemListWithFrame:NSMakeRect(256, 44, 100, 22) + selectedItem:sel]; [self addSubview:mHeaderCenterList]; mSettings->GetHeaderStrRight(sel); - mHeaderRightList = [self headerFooterItemListWithFrame:NSMakeRect(356, 44, 100, 22) - selectedItem:sel]; + mHeaderRightList = + [self headerFooterItemListWithFrame:NSMakeRect(356, 44, 100, 22) + selectedItem:sel]; [self addSubview:mHeaderRightList]; mSettings->GetFooterStrLeft(sel); - mFooterLeftList = [self headerFooterItemListWithFrame:NSMakeRect(156, 0, 100, 22) - selectedItem:sel]; + mFooterLeftList = + [self headerFooterItemListWithFrame:NSMakeRect(156, 0, 100, 22) + selectedItem:sel]; [self addSubview:mFooterLeftList]; mSettings->GetFooterStrCenter(sel); - mFooterCenterList = [self headerFooterItemListWithFrame:NSMakeRect(256, 0, 100, 22) - selectedItem:sel]; + mFooterCenterList = + [self headerFooterItemListWithFrame:NSMakeRect(256, 0, 100, 22) + selectedItem:sel]; [self addSubview:mFooterCenterList]; mSettings->GetFooterStrRight(sel); - mFooterRightList = [self headerFooterItemListWithFrame:NSMakeRect(356, 0, 100, 22) - selectedItem:sel]; + mFooterRightList = + [self headerFooterItemListWithFrame:NSMakeRect(356, 0, 100, 22) + selectedItem:sel]; [self addSubview:mFooterRightList]; } @@ -502,8 +532,9 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; - (NSString*)summaryValueForCheckbox:(NSButton*)aCheckbox { if (![aCheckbox isEnabled]) return [self localizedString:"summaryNAValue"]; - return [aCheckbox state] == NSOnState ? [self localizedString:"summaryOnValue"] - : [self localizedString:"summaryOffValue"]; + return [aCheckbox state] == NSOnState + ? [self localizedString:"summaryOnValue"] + : [self localizedString:"summaryOffValue"]; } - (NSString*)headerSummaryValue { @@ -513,7 +544,8 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; stringByAppendingString: [[mHeaderCenterList titleOfSelectedItem] stringByAppendingString: - [@", " stringByAppendingString:[mHeaderRightList titleOfSelectedItem]]]]]; + [@", " stringByAppendingString: + [mHeaderRightList titleOfSelectedItem]]]]]; } - (NSString*)footerSummaryValue { @@ -523,43 +555,49 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; stringByAppendingString: [[mFooterCenterList titleOfSelectedItem] stringByAppendingString: - [@", " stringByAppendingString:[mFooterRightList titleOfSelectedItem]]]]]; + [@", " stringByAppendingString: + [mFooterRightList titleOfSelectedItem]]]]]; } - (NSArray*)localizedSummaryItems { return [NSArray arrayWithObjects: [NSDictionary - dictionaryWithObjectsAndKeys:[self localizedString:"summarySelectionOnlyTitle"], - NSPrintPanelAccessorySummaryItemNameKey, - [self - summaryValueForCheckbox:mPrintSelectionOnlyCheckbox], - NSPrintPanelAccessorySummaryItemDescriptionKey, nil], + dictionaryWithObjectsAndKeys: + [self localizedString:"summarySelectionOnlyTitle"], + NSPrintPanelAccessorySummaryItemNameKey, + [self summaryValueForCheckbox:mPrintSelectionOnlyCheckbox], + NSPrintPanelAccessorySummaryItemDescriptionKey, nil], + [NSDictionary dictionaryWithObjectsAndKeys: + [self localizedString:"summaryShrinkToFitTitle"], + NSPrintPanelAccessorySummaryItemNameKey, + [self summaryValueForCheckbox:mShrinkToFitCheckbox], + NSPrintPanelAccessorySummaryItemDescriptionKey, + nil], [NSDictionary - dictionaryWithObjectsAndKeys:[self localizedString:"summaryShrinkToFitTitle"], - NSPrintPanelAccessorySummaryItemNameKey, - [self summaryValueForCheckbox:mShrinkToFitCheckbox], - NSPrintPanelAccessorySummaryItemDescriptionKey, nil], + dictionaryWithObjectsAndKeys: + [self localizedString:"summaryPrintBGColorsTitle"], + NSPrintPanelAccessorySummaryItemNameKey, + [self summaryValueForCheckbox:mPrintBGColorsCheckbox], + NSPrintPanelAccessorySummaryItemDescriptionKey, nil], [NSDictionary - dictionaryWithObjectsAndKeys:[self localizedString:"summaryPrintBGColorsTitle"], - NSPrintPanelAccessorySummaryItemNameKey, - [self summaryValueForCheckbox:mPrintBGColorsCheckbox], - NSPrintPanelAccessorySummaryItemDescriptionKey, nil], - [NSDictionary - dictionaryWithObjectsAndKeys:[self localizedString:"summaryPrintBGImagesTitle"], - NSPrintPanelAccessorySummaryItemNameKey, - [self summaryValueForCheckbox:mPrintBGImagesCheckbox], - NSPrintPanelAccessorySummaryItemDescriptionKey, nil], - [NSDictionary dictionaryWithObjectsAndKeys:[self localizedString:"summaryHeaderTitle"], - NSPrintPanelAccessorySummaryItemNameKey, - [self headerSummaryValue], - NSPrintPanelAccessorySummaryItemDescriptionKey, - nil], - [NSDictionary dictionaryWithObjectsAndKeys:[self localizedString:"summaryFooterTitle"], - NSPrintPanelAccessorySummaryItemNameKey, - [self footerSummaryValue], - NSPrintPanelAccessorySummaryItemDescriptionKey, - nil], + dictionaryWithObjectsAndKeys: + [self localizedString:"summaryPrintBGImagesTitle"], + NSPrintPanelAccessorySummaryItemNameKey, + [self summaryValueForCheckbox:mPrintBGImagesCheckbox], + NSPrintPanelAccessorySummaryItemDescriptionKey, nil], + [NSDictionary dictionaryWithObjectsAndKeys: + [self localizedString:"summaryHeaderTitle"], + NSPrintPanelAccessorySummaryItemNameKey, + [self headerSummaryValue], + NSPrintPanelAccessorySummaryItemDescriptionKey, + nil], + [NSDictionary dictionaryWithObjectsAndKeys: + [self localizedString:"summaryFooterTitle"], + NSPrintPanelAccessorySummaryItemNameKey, + [self footerSummaryValue], + NSPrintPanelAccessorySummaryItemDescriptionKey, + nil], nil]; } @@ -569,11 +607,13 @@ static const char sHeaderFooterTags[][4] = {"", "&T", "&U", "&D", "&P", "&PT"}; @implementation PrintPanelAccessoryController -- (id)initWithSettings:(nsIPrintSettings*)aSettings haveSelection:(bool)aHaveSelection { +- (id)initWithSettings:(nsIPrintSettings*)aSettings + haveSelection:(bool)aHaveSelection { [super initWithNibName:nil bundle:nil]; - NSView* accView = [[PrintPanelAccessoryView alloc] initWithSettings:aSettings - haveSelection:aHaveSelection]; + NSView* accView = + [[PrintPanelAccessoryView alloc] initWithSettings:aSettings + haveSelection:aHaveSelection]; [self setView:accView]; [accView release]; return self; diff --git a/widget/cocoa/nsPrintSettingsServiceX.mm b/widget/cocoa/nsPrintSettingsServiceX.mm index 75987800860c..d2cb4486af25 100644 --- a/widget/cocoa/nsPrintSettingsServiceX.mm +++ b/widget/cocoa/nsPrintSettingsServiceX.mm @@ -14,7 +14,8 @@ using namespace mozilla::embedding; NS_IMETHODIMP -nsPrintSettingsServiceX::SerializeToPrintData(nsIPrintSettings* aSettings, PrintData* data) { +nsPrintSettingsServiceX::SerializeToPrintData(nsIPrintSettings* aSettings, + PrintData* data) { nsresult rv = nsPrintSettingsService::SerializeToPrintData(aSettings, data); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -32,9 +33,10 @@ nsPrintSettingsServiceX::SerializeToPrintData(nsIPrintSettings* aSettings, Print } NS_IMETHODIMP -nsPrintSettingsServiceX::DeserializeToPrintSettings(const PrintData& data, - nsIPrintSettings* settings) { - nsresult rv = nsPrintSettingsService::DeserializeToPrintSettings(data, settings); +nsPrintSettingsServiceX::DeserializeToPrintSettings( + const PrintData& data, nsIPrintSettings* settings) { + nsresult rv = + nsPrintSettingsService::DeserializeToPrintSettings(data, settings); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -50,11 +52,13 @@ nsPrintSettingsServiceX::DeserializeToPrintSettings(const PrintData& data, return NS_OK; } -nsresult nsPrintSettingsServiceX::_CreatePrintSettings(nsIPrintSettings** _retval) { +nsresult nsPrintSettingsServiceX::_CreatePrintSettings( + nsIPrintSettings** _retval) { nsresult rv; *_retval = nullptr; - nsPrintSettingsX* printSettings = new nsPrintSettingsX; // does not initially ref count + nsPrintSettingsX* printSettings = + new nsPrintSettingsX; // does not initially ref count NS_ENSURE_TRUE(printSettings, NS_ERROR_OUT_OF_MEMORY); NS_ADDREF(*_retval = printSettings); diff --git a/widget/cocoa/nsPrintSettingsX.mm b/widget/cocoa/nsPrintSettingsX.mm index e72a7d8c1ddf..80da7309e4e6 100644 --- a/widget/cocoa/nsPrintSettingsX.mm +++ b/widget/cocoa/nsPrintSettingsX.mm @@ -45,10 +45,10 @@ nsPrintSettingsX& nsPrintSettingsX::operator=(const nsPrintSettingsX& rhs) { mDestination = rhs.mDestination; mDisposition = rhs.mDisposition; - // We don't copy mSystemPrintInfo here, so any copied printSettings will start out - // without a wrapped printInfo, just using our internal settings. The system - // printInfo is used *only* by the nsPrintSettingsX to which it was originally - // passed (when the user ran a system print UI dialog). + // We don't copy mSystemPrintInfo here, so any copied printSettings will start + // out without a wrapped printInfo, just using our internal settings. The + // system printInfo is used *only* by the nsPrintSettingsX to which it was + // originally passed (when the user ran a system print UI dialog). return *this; } @@ -134,12 +134,13 @@ NSPrintInfo* nsPrintSettingsX::CreateOrCopyPrintInfo(bool aWithScaling) { // really localize the name of this printer at some point. Once we drop // support for 10.12 we should remove this check. if (!mPrinter.EqualsLiteral("Mozilla Save to PDF")) { - [printInfo setPrinter:[NSPrinter printerWithName:nsCocoaUtils::ToNSString(mPrinter)]]; + [printInfo setPrinter:[NSPrinter printerWithName:nsCocoaUtils::ToNSString( + mPrinter)]]; } - // Scaling is handled by gecko, we do NOT want the cocoa printing system to add - // a second scaling on top of that. So we only set the true scaling factor here - // if the caller explicitly asked for it. + // Scaling is handled by gecko, we do NOT want the cocoa printing system to + // add a second scaling on top of that. So we only set the true scaling factor + // here if the caller explicitly asked for it. [printInfo setScalingFactor:CGFloat(aWithScaling ? mScaling : 1.0f)]; const bool allPages = mPageRanges.IsEmpty(); @@ -160,7 +161,8 @@ NSPrintInfo* nsPrintSettingsX::CreateOrCopyPrintInfo(bool aWithScaling) { NSURL* jobSavingURL = nullptr; if (!mToFileName.IsEmpty()) { - jobSavingURL = [NSURL fileURLWithPath:nsCocoaUtils::ToNSString(mToFileName)]; + jobSavingURL = + [NSURL fileURLWithPath:nsCocoaUtils::ToNSString(mToFileName)]; if (jobSavingURL) { // Note: the PMPrintSettingsSetJobName call in nsPrintDialogServiceX::Show // seems to mean that we get a sensible file name pre-populated in the @@ -205,12 +207,15 @@ NSPrintInfo* nsPrintSettingsX::CreateOrCopyPrintInfo(bool aWithScaling) { forKey:@"com_apple_print_PrintSettings_PMDuplexing"]; if (mDestination != kPMDestinationInvalid) { - // Required to support PDF-workflow destinations such as Save to Web Receipts. - [printSettings setObject:[NSNumber numberWithUnsignedShort:mDestination] - forKey:@"com_apple_print_PrintSettings_PMDestinationType"]; + // Required to support PDF-workflow destinations such as Save to Web + // Receipts. + [printSettings + setObject:[NSNumber numberWithUnsignedShort:mDestination] + forKey:@"com_apple_print_PrintSettings_PMDestinationType"]; if (jobSavingURL) { - [printSettings setObject:[jobSavingURL absoluteString] - forKey:@"com_apple_print_PrintSettings_PMOutputFilename"]; + [printSettings + setObject:[jobSavingURL absoluteString] + forKey:@"com_apple_print_PrintSettings_PMOutputFilename"]; } } @@ -230,7 +235,8 @@ NSPrintInfo* nsPrintSettingsX::CreateOrCopyPrintInfo(bool aWithScaling) { NS_OBJC_END_TRY_BLOCK_RETURN(nullptr); } -void nsPrintSettingsX::SetFromPrintInfo(NSPrintInfo* aPrintInfo, bool aAdoptPrintInfo) { +void nsPrintSettingsX::SetFromPrintInfo(NSPrintInfo* aPrintInfo, + bool aAdoptPrintInfo) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; // Set page-size/margins. @@ -242,7 +248,8 @@ void nsPrintSettingsX::SetFromPrintInfo(NSPrintInfo* aPrintInfo, bool aAdoptPrin // of paper, then our page format must also be portrait-mode; unless we've // got a pages-per-sheet value with orthogonal pages/sheets, in which case // it's reversed. - const bool arePagesPortraitMode = (areSheetsOfPaperPortraitMode != HasOrthogonalSheetsAndPages()); + const bool arePagesPortraitMode = + (areSheetsOfPaperPortraitMode != HasOrthogonalSheetsAndPages()); if (arePagesPortraitMode) { mOrientation = nsIPrintSettings::kPortraitOrientation; @@ -260,8 +267,8 @@ void nsPrintSettingsX::SetFromPrintInfo(NSPrintInfo* aPrintInfo, bool aAdoptPrin mUnwriteableMargin.left = static_cast([aPrintInfo leftMargin]); if (aAdoptPrintInfo) { - // Keep a reference to the printInfo; it may have settings that we don't know how to handle - // otherwise. + // Keep a reference to the printInfo; it may have settings that we don't + // know how to handle otherwise. if (mSystemPrintInfo != aPrintInfo) { if (mSystemPrintInfo) { [mSystemPrintInfo release]; @@ -295,7 +302,8 @@ void nsPrintSettingsX::SetFromPrintInfo(NSPrintInfo* aPrintInfo, bool aAdoptPrin }(); NSDictionary* dict = [aPrintInfo dictionary]; - const char* filePath = [[dict objectForKey:NSPrintJobSavingURL] fileSystemRepresentation]; + const char* filePath = + [[dict objectForKey:NSPrintJobSavingURL] fileSystemRepresentation]; if (filePath && *filePath) { CopyUTF8toUTF16(Span(filePath, strlen(filePath)), mToFileName); } @@ -310,7 +318,8 @@ void nsPrintSettingsX::SetFromPrintInfo(NSPrintInfo* aPrintInfo, bool aAdoptPrin } NSDictionary* printSettings = [aPrintInfo printSettings]; - NSNumber* value = [printSettings objectForKey:@"com_apple_print_PrintSettings_PMDuplexing"]; + NSNumber* value = + [printSettings objectForKey:@"com_apple_print_PrintSettings_PMDuplexing"]; if (value) { PMDuplexMode duplexSetting = [value unsignedShortValue]; switch (duplexSetting) { @@ -334,7 +343,8 @@ void nsPrintSettingsX::SetFromPrintInfo(NSPrintInfo* aPrintInfo, bool aAdoptPrin mDuplex = kDuplexNone; } - value = [printSettings objectForKey:@"com_apple_print_PrintSettings_PMDestinationType"]; + value = [printSettings + objectForKey:@"com_apple_print_PrintSettings_PMDestinationType"]; if (value) { mDestination = [value unsignedShortValue]; } diff --git a/widget/cocoa/nsSandboxViolationSink.mm b/widget/cocoa/nsSandboxViolationSink.mm index 1399536d6ef7..611e0387b194 100644 --- a/widget/cocoa/nsSandboxViolationSink.mm +++ b/widget/cocoa/nsSandboxViolationSink.mm @@ -22,11 +22,12 @@ void nsSandboxViolationSink::Start() { if (mNotifyToken) { return; } - notify_register_dispatch( - SANDBOX_VIOLATION_NOTIFICATION_NAME, &mNotifyToken, - dispatch_queue_create(SANDBOX_VIOLATION_QUEUE_NAME, DISPATCH_QUEUE_SERIAL), ^(int token) { - ViolationHandler(); - }); + notify_register_dispatch(SANDBOX_VIOLATION_NOTIFICATION_NAME, &mNotifyToken, + dispatch_queue_create(SANDBOX_VIOLATION_QUEUE_NAME, + DISPATCH_QUEUE_SERIAL), + ^(int token) { + ViolationHandler(); + }); } void nsSandboxViolationSink::Stop() { @@ -50,19 +51,22 @@ void nsSandboxViolationSink::Stop() { void nsSandboxViolationSink::ViolationHandler() { aslmsg query = asl_new(ASL_TYPE_QUERY); - asl_set_query(query, ASL_KEY_FACILITY, "com.apple.sandbox", ASL_QUERY_OP_EQUAL); + asl_set_query(query, ASL_KEY_FACILITY, "com.apple.sandbox", + ASL_QUERY_OP_EQUAL); // Only get reports that were generated very recently. char query_time[30] = {0}; SprintfLiteral(query_time, "%li", time(NULL) - 2); - asl_set_query(query, ASL_KEY_TIME, query_time, ASL_QUERY_OP_NUMERIC | ASL_QUERY_OP_GREATER_EQUAL); + asl_set_query(query, ASL_KEY_TIME, query_time, + ASL_QUERY_OP_NUMERIC | ASL_QUERY_OP_GREATER_EQUAL); // This code is easier to test if we don't just track "our" violations, // which are (normally) few and far between. For example (for the time // being at least) four appleeventsd sandbox violations happen every time // we start the browser in e10s mode. But it makes sense to default to // only tracking "our" violations. - if (mozilla::Preferences::GetBool("security.sandbox.mac.track.violations.oursonly", true)) { + if (mozilla::Preferences::GetBool( + "security.sandbox.mac.track.violations.oursonly", true)) { // This makes each of our processes log its own violations. It might // be better to make the chrome process log all the other processes' // violations. @@ -99,8 +103,9 @@ void nsSandboxViolationSink::ViolationHandler() { const char* pid_str = asl_get(found, ASL_KEY_REF_PID); const char* message_str = asl_get(found, ASL_KEY_MSG); - NSLog(@"nsSandboxViolationSink::ViolationHandler(): id %s, pid %s, message %s", id_str, - pid_str, message_str); + NSLog(@"nsSandboxViolationSink::ViolationHandler(): id %s, pid %s, " + @"message %s", + id_str, pid_str, message_str); } aslresponse_free(response); } diff --git a/widget/cocoa/nsSound.mm b/widget/cocoa/nsSound.mm index fb979f6f375e..cbaad44be7a3 100644 --- a/widget/cocoa/nsSound.mm +++ b/widget/cocoa/nsSound.mm @@ -31,8 +31,9 @@ nsSound::Beep() { } NS_IMETHODIMP -nsSound::OnStreamComplete(nsIStreamLoader* aLoader, nsISupports* context, nsresult aStatus, - uint32_t dataLen, const uint8_t* data) { +nsSound::OnStreamComplete(nsIStreamLoader* aLoader, nsISupports* context, + nsresult aStatus, uint32_t dataLen, + const uint8_t* data) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; NSData* value = [NSData dataWithBytes:data length:dataLen]; @@ -52,11 +53,12 @@ NS_IMETHODIMP nsSound::Play(nsIURL* aURL) { nsCOMPtr uri(aURL); nsCOMPtr loader; - return NS_NewStreamLoader(getter_AddRefs(loader), uri, - this, // aObserver - nsContentUtils::GetSystemPrincipal(), - nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, - nsIContentPolicy::TYPE_OTHER); + return NS_NewStreamLoader( + getter_AddRefs(loader), uri, + this, // aObserver + nsContentUtils::GetSystemPrincipal(), + nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, + nsIContentPolicy::TYPE_OTHER); } NS_IMETHODIMP diff --git a/widget/cocoa/nsStandaloneNativeMenu.mm b/widget/cocoa/nsStandaloneNativeMenu.mm index d672f33314f1..d5a70f817e59 100644 --- a/widget/cocoa/nsStandaloneNativeMenu.mm +++ b/widget/cocoa/nsStandaloneNativeMenu.mm @@ -39,7 +39,8 @@ nsStandaloneNativeMenu::Init(Element* aElement) { NS_IMETHODIMP nsStandaloneNativeMenu::MenuWillOpen(bool* aResult) { - NS_ASSERTION(mMenu != nullptr, "nsStandaloneNativeMenu::OnOpen - mMenu is null!"); + NS_ASSERTION(mMenu != nullptr, + "nsStandaloneNativeMenu::OnOpen - mMenu is null!"); mMenu->MenuWillOpen(); @@ -48,7 +49,8 @@ nsStandaloneNativeMenu::MenuWillOpen(bool* aResult) { } NS_IMETHODIMP -nsStandaloneNativeMenu::ActivateNativeMenuItemAt(const nsAString& aIndexString) { +nsStandaloneNativeMenu::ActivateNativeMenuItemAt( + const nsAString& aIndexString) { if (!mMenu) { return NS_ERROR_NOT_INITIALIZED; } diff --git a/widget/cocoa/nsSystemStatusBarCocoa.mm b/widget/cocoa/nsSystemStatusBarCocoa.mm index 6261a4b0c409..f46ee0ce3e9c 100644 --- a/widget/cocoa/nsSystemStatusBarCocoa.mm +++ b/widget/cocoa/nsSystemStatusBarCocoa.mm @@ -36,13 +36,14 @@ nsSystemStatusBarCocoa::RemoveItem(Element* aElement) { return NS_OK; } -nsSystemStatusBarCocoa::StatusItem::StatusItem(NativeMenuMac* aMenu) : mMenu(aMenu) { +nsSystemStatusBarCocoa::StatusItem::StatusItem(NativeMenuMac* aMenu) + : mMenu(aMenu) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK; MOZ_COUNT_CTOR(nsSystemStatusBarCocoa::StatusItem); - mStatusItem = - [[NSStatusBar.systemStatusBar statusItemWithLength:NSSquareStatusItemLength] retain]; + mStatusItem = [[NSStatusBar.systemStatusBar + statusItemWithLength:NSSquareStatusItemLength] retain]; mStatusItem.menu = mMenu->NativeNSMenu(); mStatusItem.highlightMode = YES; diff --git a/widget/cocoa/nsToolkit.mm b/widget/cocoa/nsToolkit.mm index 01802620679e..065100a10728 100644 --- a/widget/cocoa/nsToolkit.mm +++ b/widget/cocoa/nsToolkit.mm @@ -45,7 +45,9 @@ static io_connect_t gRootPort = MACH_PORT_NULL; nsToolkit* nsToolkit::gToolkit = nullptr; nsToolkit::nsToolkit() - : mSleepWakeNotificationRLS(nullptr), mPowerNotifier{0}, mAllProcessMouseMonitor(nil) { + : mSleepWakeNotificationRLS(nullptr), + mPowerNotifier{0}, + mAllProcessMouseMonitor(nil) { MOZ_COUNT_CTOR(nsToolkit); RegisterForSleepWakeNotifications(); } @@ -58,11 +60,13 @@ nsToolkit::~nsToolkit() { void nsToolkit::PostSleepWakeNotification(const char* aNotification) { nsCOMPtr observerService = services::GetObserverService(); - if (observerService) observerService->NotifyObservers(nullptr, aNotification, nullptr); + if (observerService) + observerService->NotifyObservers(nullptr, aNotification, nullptr); } // http://developer.apple.com/documentation/DeviceDrivers/Conceptual/IOKitFundamentals/PowerMgmt/chapter_10_section_3.html -static void ToolkitSleepWakeCallback(void* refCon, io_service_t service, natural_t messageType, +static void ToolkitSleepWakeCallback(void* refCon, io_service_t service, + natural_t messageType, void* messageArgument) { NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; @@ -98,15 +102,17 @@ nsresult nsToolkit::RegisterForSleepWakeNotifications() { NS_ASSERTION(!mSleepWakeNotificationRLS, "Already registered for sleep/wake"); - gRootPort = - ::IORegisterForSystemPower(0, ¬ifyPortRef, ToolkitSleepWakeCallback, &mPowerNotifier); + gRootPort = ::IORegisterForSystemPower( + 0, ¬ifyPortRef, ToolkitSleepWakeCallback, &mPowerNotifier); if (gRootPort == MACH_PORT_NULL) { NS_ERROR("IORegisterForSystemPower failed"); return NS_ERROR_FAILURE; } - mSleepWakeNotificationRLS = ::IONotificationPortGetRunLoopSource(notifyPortRef); - ::CFRunLoopAddSource(::CFRunLoopGetCurrent(), mSleepWakeNotificationRLS, kCFRunLoopDefaultMode); + mSleepWakeNotificationRLS = + ::IONotificationPortGetRunLoopSource(notifyPortRef); + ::CFRunLoopAddSource(::CFRunLoopGetCurrent(), mSleepWakeNotificationRLS, + kCFRunLoopDefaultMode); return NS_OK; @@ -146,14 +152,16 @@ void nsToolkit::MonitorAllProcessMouseEvents() { if (mAllProcessMouseMonitor == nil) { mAllProcessMouseMonitor = [NSEvent - addGlobalMonitorForEventsMatchingMask:NSEventMaskLeftMouseDown | NSEventMaskLeftMouseDown + addGlobalMonitorForEventsMatchingMask:NSEventMaskLeftMouseDown | + NSEventMaskLeftMouseDown handler:^(NSEvent* evt) { if ([NSApp isActive]) { return; } nsIRollupListener* rollupListener = - nsBaseWidget::GetActiveRollupListener(); + nsBaseWidget:: + GetActiveRollupListener(); if (!rollupListener) { return; } @@ -165,17 +173,22 @@ void nsToolkit::MonitorAllProcessMouseEvents() { } NSWindow* ctxMenuWindow = - (NSWindow*)rollupWidget->GetNativeData( - NS_NATIVE_WINDOW); + (NSWindow*) + rollupWidget->GetNativeData( + NS_NATIVE_WINDOW); if (!ctxMenuWindow) { return; } - // Don't roll up the rollup widget if our mouseDown happens - // over it (doing so would break the corresponding context - // menu). - NSPoint screenLocation = [NSEvent mouseLocation]; - if (NSPointInRect(screenLocation, [ctxMenuWindow frame])) { + // Don't roll up the rollup widget if + // our mouseDown happens over it (doing + // so would break the corresponding + // context menu). + NSPoint screenLocation = + [NSEvent mouseLocation]; + if (NSPointInRect( + screenLocation, + [ctxMenuWindow frame])) { return; } @@ -216,9 +229,9 @@ nsToolkit* nsToolkit::GetToolkit() { // Leopard and is available to 64-bit binaries on Leopard and above. Based on // ideas and code from http://www.cocoadev.com/index.pl?MethodSwizzling. // Since the Method type becomes an opaque type as of Objective-C 2.0, we'll -// have to switch to using accessor methods like method_exchangeImplementations() -// when we build 64-bit binaries that use Objective-C 2.0 (on and for Leopard -// and above). +// have to switch to using accessor methods like +// method_exchangeImplementations() when we build 64-bit binaries that use +// Objective-C 2.0 (on and for Leopard and above). // // Be aware that, if aClass doesn't have an orgMethod selector but one of its // superclasses does, the method substitution will (in effect) take place in diff --git a/widget/cocoa/nsTouchBar.mm b/widget/cocoa/nsTouchBar.mm index f6a704238145..067ce0312986 100644 --- a/widget/cocoa/nsTouchBar.mm +++ b/widget/cocoa/nsTouchBar.mm @@ -49,10 +49,11 @@ static const uint32_t kInputIconSize = 16; self.customizationAllowedItemIdentifiers = @[]; if (!aInputs) { - // This customization identifier is how users' custom layouts are saved by macOS. - // If this changes, all users' layouts would be reset to the default layout. - self.customizationIdentifier = - [kTouchBarBaseIdentifier stringByAppendingPathExtension:@"defaultbar"]; + // This customization identifier is how users' custom layouts are saved by + // macOS. If this changes, all users' layouts would be reset to the + // default layout. + self.customizationIdentifier = [kTouchBarBaseIdentifier + stringByAppendingPathExtension:@"defaultbar"]; nsCOMPtr allItems; nsresult rv = mTouchBarHelper->GetAllItems(getter_AddRefs(allItems)); @@ -65,7 +66,8 @@ static const uint32_t kInputIconSize = 16; // This is copied to self.customizationAllowedItemIdentifiers. // Required since [self.mappedItems allKeys] does not preserve order. // One slot is added for the spacer item. - NSMutableArray* orderedIdentifiers = [NSMutableArray arrayWithCapacity:itemCount + 1]; + NSMutableArray* orderedIdentifiers = + [NSMutableArray arrayWithCapacity:itemCount + 1]; for (uint32_t i = 0; i < itemCount; ++i) { nsCOMPtr input = do_QueryElementAt(allItems, i); if (!input) { @@ -79,15 +81,17 @@ static const uint32_t kInputIconSize = 16; continue; } - // If there is already an input in mappedLayoutItems with this identifier, - // that means updateItem fired before this initialization. The input - // cached by updateItem is more current, so we should use that one. + // If there is already an input in mappedLayoutItems with this + // identifier, that means updateItem fired before this initialization. + // The input cached by updateItem is more current, so we should use that + // one. if (self.mappedLayoutItems[newInputIdentifier]) { convertedInput = self.mappedLayoutItems[newInputIdentifier]; } else { convertedInput = [[TouchBarInput alloc] initWithXPCOM:input]; // Add new input to dictionary for lookup of properties in delegate. - self.mappedLayoutItems[[convertedInput nativeIdentifier]] = convertedInput; + self.mappedLayoutItems[[convertedInput nativeIdentifier]] = + convertedInput; } orderedIdentifiers[i] = [convertedInput nativeIdentifier]; @@ -99,13 +103,16 @@ static const uint32_t kInputIconSize = 16; [TouchBarInput nativeIdentifierWithType:@"button" withKey:@"back"], [TouchBarInput nativeIdentifierWithType:@"button" withKey:@"forward"], [TouchBarInput nativeIdentifierWithType:@"button" withKey:@"reload"], - [TouchBarInput nativeIdentifierWithType:@"mainButton" withKey:@"open-location"], + [TouchBarInput nativeIdentifierWithType:@"mainButton" + withKey:@"open-location"], [TouchBarInput nativeIdentifierWithType:@"button" withKey:@"new-tab"], - [TouchBarInput shareScrubberIdentifier], [TouchBarInput searchPopoverIdentifier] + [TouchBarInput shareScrubberIdentifier], + [TouchBarInput searchPopoverIdentifier] ]; self.defaultItemIdentifiers = [defaultItemIdentifiers copy]; } else { - NSMutableArray* defaultItemIdentifiers = [NSMutableArray arrayWithCapacity:[aInputs count]]; + NSMutableArray* defaultItemIdentifiers = + [NSMutableArray arrayWithCapacity:[aInputs count]]; for (TouchBarInput* input in aInputs) { self.mappedLayoutItems[[input nativeIdentifier]] = input; [defaultItemIdentifiers addObject:[input nativeIdentifier]]; @@ -156,7 +163,8 @@ static const uint32_t kInputIconSize = 16; if ([input baseType] == TouchBarInputBaseType::kScrubber) { // We check the identifier rather than the baseType here as a special case. - if (![aIdentifier isEqualToString:[TouchBarInput shareScrubberIdentifier]]) { + if (![aIdentifier + isEqualToString:[TouchBarInput shareScrubberIdentifier]]) { // We're only supporting the Share scrubber for now. return nil; } @@ -170,13 +178,15 @@ static const uint32_t kInputIconSize = 16; // We initialize popoverTouchBar here because we only allow setting this // property on popover creation. Updating popoverTouchBar for every update // of the popover item would be very expensive. - newPopoverItem.popoverTouchBar = [[nsTouchBar alloc] initWithInputs:[input children]]; + newPopoverItem.popoverTouchBar = + [[nsTouchBar alloc] initWithInputs:[input children]]; [self updatePopover:newPopoverItem withIdentifier:[input nativeIdentifier]]; return newPopoverItem; } // Our new item, which will be initialized depending on aIdentifier. - NSCustomTouchBarItem* newItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:aIdentifier]; + NSCustomTouchBarItem* newItem = + [[NSCustomTouchBarItem alloc] initWithIdentifier:aIdentifier]; [newItem setCustomizationLabel:[input title]]; if ([input baseType] == TouchBarInputBaseType::kScrollView) { @@ -190,7 +200,9 @@ static const uint32_t kInputIconSize = 16; } // The cases of a button or main button require the same setup. - NSButton* button = [NSButton buttonWithTitle:@"" target:self action:@selector(touchBarAction:)]; + NSButton* button = [NSButton buttonWithTitle:@"" + target:self + action:@selector(touchBarAction:)]; newItem.view = button; if ([input baseType] == TouchBarInputBaseType::kButton && @@ -229,21 +241,27 @@ static const uint32_t kInputIconSize = 16; if ([aInput baseType] == TouchBarInputBaseType::kButton) { [(NSCustomTouchBarItem*)item setCustomizationLabel:[aInput title]]; - [self updateButton:(NSCustomTouchBarItem*)item withIdentifier:[aInput nativeIdentifier]]; + [self updateButton:(NSCustomTouchBarItem*)item + withIdentifier:[aInput nativeIdentifier]]; } else if ([aInput baseType] == TouchBarInputBaseType::kMainButton) { [(NSCustomTouchBarItem*)item setCustomizationLabel:[aInput title]]; - [self updateMainButton:(NSCustomTouchBarItem*)item withIdentifier:[aInput nativeIdentifier]]; + [self updateMainButton:(NSCustomTouchBarItem*)item + withIdentifier:[aInput nativeIdentifier]]; } else if ([aInput baseType] == TouchBarInputBaseType::kScrollView) { [(NSCustomTouchBarItem*)item setCustomizationLabel:[aInput title]]; - [self updateScrollView:(NSCustomTouchBarItem*)item withIdentifier:[aInput nativeIdentifier]]; + [self updateScrollView:(NSCustomTouchBarItem*)item + withIdentifier:[aInput nativeIdentifier]]; } else if ([aInput baseType] == TouchBarInputBaseType::kPopover) { [(NSPopoverTouchBarItem*)item setCustomizationLabel:[aInput title]]; - [self updatePopover:(NSPopoverTouchBarItem*)item withIdentifier:[aInput nativeIdentifier]]; + [self updatePopover:(NSPopoverTouchBarItem*)item + withIdentifier:[aInput nativeIdentifier]]; for (TouchBarInput* child in [aInput children]) { - [(nsTouchBar*)[(NSPopoverTouchBarItem*)item popoverTouchBar] updateItem:child]; + [(nsTouchBar*)[(NSPopoverTouchBarItem*)item popoverTouchBar] + updateItem:child]; } } else if ([aInput baseType] == TouchBarInputBaseType::kLabel) { - [self updateLabel:(NSTextField*)item.view withIdentifier:[aInput nativeIdentifier]]; + [self updateLabel:(NSTextField*)item.view + withIdentifier:[aInput nativeIdentifier]]; } return true; @@ -255,9 +273,11 @@ static const uint32_t kInputIconSize = 16; if ([potentialPopover baseType] != TouchBarInputBaseType::kPopover) { continue; } - NSTouchBarItem* popover = [self itemForIdentifier:[potentialPopover nativeIdentifier]]; + NSTouchBarItem* popover = + [self itemForIdentifier:[potentialPopover nativeIdentifier]]; if (popover) { - if ([(nsTouchBar*)[(NSPopoverTouchBarItem*)popover popoverTouchBar] updateItem:aInput]) { + if ([(nsTouchBar*)[(NSPopoverTouchBarItem*)popover popoverTouchBar] + updateItem:aInput]) { return true; } } @@ -266,14 +286,18 @@ static const uint32_t kInputIconSize = 16; } - (bool)maybeUpdateScrollViewChild:(TouchBarInput*)aInput { - NSCustomTouchBarItem* scrollViewButton = self.scrollViewButtons[[aInput nativeIdentifier]]; + NSCustomTouchBarItem* scrollViewButton = + self.scrollViewButtons[[aInput nativeIdentifier]]; if (scrollViewButton) { // ScrollView buttons are similar to mainButtons except for their width. - [self updateMainButton:scrollViewButton withIdentifier:[aInput nativeIdentifier]]; + [self updateMainButton:scrollViewButton + withIdentifier:[aInput nativeIdentifier]]; NSButton* button = (NSButton*)scrollViewButton.view; - uint32_t buttonSize = MAX(button.attributedTitle.size.width + kInputIconSize + kInputSpacing, - kScrollViewButtonWidth); - [[button widthAnchor] constraintGreaterThanOrEqualToConstant:buttonSize].active = YES; + uint32_t buttonSize = + MAX(button.attributedTitle.size.width + kInputIconSize + kInputSpacing, + kScrollViewButtonWidth); + [[button widthAnchor] constraintGreaterThanOrEqualToConstant:buttonSize] + .active = YES; } // Updating the TouchBarInput* in the ScrollView's mChildren array. for (NSTouchBarItemIdentifier identifier in self.mappedLayoutItems) { @@ -283,7 +307,8 @@ static const uint32_t kInputIconSize = 16; } for (uint32_t i = 0; i < [[potentialScrollView children] count]; ++i) { TouchBarInput* child = [potentialScrollView children][i]; - if (![[child nativeIdentifier] isEqualToString:[aInput nativeIdentifier]]) { + if (![[child nativeIdentifier] + isEqualToString:[aInput nativeIdentifier]]) { continue; } [[potentialScrollView children] replaceObjectAtIndex:i withObject:aInput]; @@ -316,7 +341,8 @@ static const uint32_t kInputIconSize = 16; [button setImagePosition:NSImageOnly]; [self loadIconForInput:input forItem:aButton]; // Because we are hiding the title, NSAccessibility also does not get it. - // Therefore, set an accessibility label as alternative text for image-only buttons. + // Therefore, set an accessibility label as alternative text for image-only + // buttons. [button setAccessibilityLabel:[input title]]; } @@ -350,8 +376,10 @@ static const uint32_t kInputIconSize = 16; [button setImagePosition:NSImageLeft]; } button.imageHugsTitle = YES; - [button.widthAnchor constraintGreaterThanOrEqualToConstant:MAIN_BUTTON_WIDTH].active = YES; - [button setContentHuggingPriority:1.0 forOrientation:NSLayoutConstraintOrientationHorizontal]; + [button.widthAnchor constraintGreaterThanOrEqualToConstant:MAIN_BUTTON_WIDTH] + .active = YES; + [button setContentHuggingPriority:1.0 + forOrientation:NSLayoutConstraintOrientationHorizontal]; } - (void)updatePopover:(NSPopoverTouchBarItem*)aPopoverItem @@ -373,7 +401,8 @@ static const uint32_t kInputIconSize = 16; } // Special handling to show/hide the search popover if the Urlbar is focused. - if ([[input nativeIdentifier] isEqualToString:[TouchBarInput searchPopoverIdentifier]]) { + if ([[input nativeIdentifier] + isEqualToString:[TouchBarInput searchPopoverIdentifier]]) { // We can reach this code during window shutdown. We only want to toggle // showPopover if we are in a normal running state. if (!mTouchBarHelper) { @@ -404,48 +433,56 @@ static const uint32_t kInputIconSize = 16; NSSize size = NSMakeSize(kInputSpacing, 30); // Layout strings allow only alphanumeric characters. We will use this // NSCharacterSet to strip illegal characters. - NSCharacterSet* charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet]; + NSCharacterSet* charactersToRemove = + [[NSCharacterSet alphanumericCharacterSet] invertedSet]; for (TouchBarInput* childInput in [input children]) { if ([childInput baseType] != TouchBarInputBaseType::kButton) { continue; } [self replaceMappedLayoutItem:childInput]; - NSCustomTouchBarItem* newItem = - [[NSCustomTouchBarItem alloc] initWithIdentifier:[childInput nativeIdentifier]]; + NSCustomTouchBarItem* newItem = [[NSCustomTouchBarItem alloc] + initWithIdentifier:[childInput nativeIdentifier]]; NSButton* button = [NSButton buttonWithTitle:[childInput title] target:self action:@selector(touchBarAction:)]; newItem.view = button; // ScrollView buttons are similar to mainButtons except for their width. - [self updateMainButton:newItem withIdentifier:[childInput nativeIdentifier]]; - uint32_t buttonSize = MAX(button.attributedTitle.size.width + kInputIconSize + kInputSpacing, - kScrollViewButtonWidth); - [[button widthAnchor] constraintGreaterThanOrEqualToConstant:buttonSize].active = YES; + [self updateMainButton:newItem + withIdentifier:[childInput nativeIdentifier]]; + uint32_t buttonSize = + MAX(button.attributedTitle.size.width + kInputIconSize + kInputSpacing, + kScrollViewButtonWidth); + [[button widthAnchor] constraintGreaterThanOrEqualToConstant:buttonSize] + .active = YES; - NSCustomTouchBarItem* tempItem = self.scrollViewButtons[[childInput nativeIdentifier]]; + NSCustomTouchBarItem* tempItem = + self.scrollViewButtons[[childInput nativeIdentifier]]; self.scrollViewButtons[[childInput nativeIdentifier]] = newItem; [tempItem release]; button.translatesAutoresizingMaskIntoConstraints = NO; [documentView addSubview:button]; NSString* layoutKey = [[[childInput nativeIdentifier] - componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""]; + componentsSeparatedByCharactersInSet:charactersToRemove] + componentsJoinedByString:@""]; // Iteratively create our layout string. - layoutFormat = - [layoutFormat stringByAppendingString:[NSString stringWithFormat:@"[%@]-8-", layoutKey]]; + layoutFormat = [layoutFormat + stringByAppendingString:[NSString + stringWithFormat:@"[%@]-8-", layoutKey]]; [constraintViews setObject:button forKey:layoutKey]; size.width += kInputSpacing + buttonSize; } - layoutFormat = [layoutFormat stringByAppendingString:[NSString stringWithFormat:@"|"]]; - NSArray* hConstraints = - [NSLayoutConstraint constraintsWithVisualFormat:layoutFormat - options:NSLayoutFormatAlignAllCenterY - metrics:nil - views:constraintViews]; - NSScrollView* scrollView = - [[NSScrollView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)]; + layoutFormat = + [layoutFormat stringByAppendingString:[NSString stringWithFormat:@"|"]]; + NSArray* hConstraints = [NSLayoutConstraint + constraintsWithVisualFormat:layoutFormat + options:NSLayoutFormatAlignAllCenterY + metrics:nil + views:constraintViews]; + NSScrollView* scrollView = [[NSScrollView alloc] + initWithFrame:CGRectMake(0, 0, size.width, size.height)]; [documentView setFrame:NSMakeRect(0, 0, size.width, size.height)]; [NSLayoutConstraint activateConstraints:hConstraints]; scrollView.documentView = documentView; @@ -453,7 +490,8 @@ static const uint32_t kInputIconSize = 16; aScrollViewItem.view = scrollView; } -- (void)updateLabel:(NSTextField*)aLabel withIdentifier:(NSTouchBarItemIdentifier)aIdentifier { +- (void)updateLabel:(NSTextField*)aLabel + withIdentifier:(NSTouchBarItemIdentifier)aIdentifier { if (!aLabel || !aIdentifier) { return; } @@ -465,11 +503,13 @@ static const uint32_t kInputIconSize = 16; [aLabel setStringValue:[input title]]; } -- (NSTouchBarItem*)makeShareScrubberForIdentifier:(NSTouchBarItemIdentifier)aIdentifier { +- (NSTouchBarItem*)makeShareScrubberForIdentifier: + (NSTouchBarItemIdentifier)aIdentifier { TouchBarInput* input = self.mappedLayoutItems[aIdentifier]; // System-default share menu NSSharingServicePickerTouchBarItem* servicesItem = - [[NSSharingServicePickerTouchBarItem alloc] initWithIdentifier:aIdentifier]; + [[NSSharingServicePickerTouchBarItem alloc] + initWithIdentifier:aIdentifier]; // buttonImage needs to be set to nil while we wait for our icon to load. // Otherwise, the default Apple share icon is automatically loaded. @@ -485,8 +525,8 @@ static const uint32_t kInputIconSize = 16; if (!aPopover) { return; } - NSPopoverTouchBarItem* popoverItem = - (NSPopoverTouchBarItem*)[self itemForIdentifier:[aPopover nativeIdentifier]]; + NSPopoverTouchBarItem* popoverItem = (NSPopoverTouchBarItem*)[self + itemForIdentifier:[aPopover nativeIdentifier]]; if (!popoverItem) { return; } @@ -548,10 +588,13 @@ static const uint32_t kInputIconSize = 16; // Childless popovers contain the default Touch Bar as its popoverTouchBar. // We check for [input children] since the default Touch Bar contains a - // popover (search-popover), so this would infinitely loop if there was no check. - if ([input baseType] == TouchBarInputBaseType::kPopover && [input children]) { + // popover (search-popover), so this would infinitely loop if there was no + // check. + if ([input baseType] == TouchBarInputBaseType::kPopover && + [input children]) { NSTouchBarItem* item = [self itemForIdentifier:identifier]; - [(nsTouchBar*)[(NSPopoverTouchBarItem*)item popoverTouchBar] releaseJSObjects]; + [(nsTouchBar*)[(NSPopoverTouchBarItem*)item popoverTouchBar] + releaseJSObjects]; } [input releaseJSObjects]; @@ -587,9 +630,10 @@ static const uint32_t kInputIconSize = 16; return @[ urlToShare, titleToShare ]; } -- (NSArray*)sharingServicePicker:(NSSharingServicePicker*)aSharingServicePicker - sharingServicesForItems:(NSArray*)aItems - proposedSharingServices:(NSArray*)aProposedServices { +- (NSArray*) + sharingServicePicker:(NSSharingServicePicker*)aSharingServicePicker + sharingServicesForItems:(NSArray*)aItems + proposedSharingServices:(NSArray*)aProposedServices { // redundant services NSArray* excludedServices = @[ @"com.apple.share.System.add-to-safari-reading-list", @@ -597,7 +641,8 @@ static const uint32_t kInputIconSize = 16; NSArray* sharingServices = [aProposedServices filteredArrayUsingPredicate:[NSPredicate - predicateWithFormat:@"NOT (name IN %@)", excludedServices]]; + predicateWithFormat:@"NOT (name IN %@)", + excludedServices]]; return sharingServices; } diff --git a/widget/cocoa/nsTouchBarInput.mm b/widget/cocoa/nsTouchBarInput.mm index dc50c64e1bc0..c2d98a99861b 100644 --- a/widget/cocoa/nsTouchBarInput.mm +++ b/widget/cocoa/nsTouchBarInput.mm @@ -99,21 +99,24 @@ [self setImageURI:aImageURI]; [self setCallback:aCallback]; if (aColor) { - [self setColor:[NSColor colorWithDisplayP3Red:((aColor >> 16) & 0xFF) / 255.0 - green:((aColor >> 8) & 0xFF) / 255.0 - blue:((aColor)&0xFF) / 255.0 - alpha:1.0]]; + [self setColor:[NSColor + colorWithDisplayP3Red:((aColor >> 16) & 0xFF) / 255.0 + green:((aColor >> 8) & 0xFF) / 255.0 + blue:((aColor)&0xFF) / 255.0 + alpha:1.0]]; } if (aChildren) { uint32_t itemCount = 0; aChildren->GetLength(&itemCount); - NSMutableArray* orderedChildren = [NSMutableArray arrayWithCapacity:itemCount]; + NSMutableArray* orderedChildren = + [NSMutableArray arrayWithCapacity:itemCount]; for (uint32_t i = 0; i < itemCount; ++i) { nsCOMPtr child = do_QueryElementAt(aChildren, i); if (!child) { continue; } - TouchBarInput* convertedChild = [[TouchBarInput alloc] initWithXPCOM:child]; + TouchBarInput* convertedChild = + [[TouchBarInput alloc] initWithXPCOM:child]; if (convertedChild) { orderedChildren[i] = convertedChild; } @@ -207,7 +210,8 @@ [super dealloc]; } -+ (NSTouchBarItemIdentifier)nativeIdentifierWithType:(NSString*)aType withKey:(NSString*)aKey { ++ (NSTouchBarItemIdentifier)nativeIdentifierWithType:(NSString*)aType + withKey:(NSString*)aKey { NSTouchBarItemIdentifier identifier; identifier = [kTouchBarBaseIdentifier stringByAppendingPathExtension:aType]; if (aKey) { @@ -216,7 +220,8 @@ return identifier; } -+ (NSTouchBarItemIdentifier)nativeIdentifierWithXPCOM:(nsCOMPtr)aInput { ++ (NSTouchBarItemIdentifier)nativeIdentifierWithXPCOM: + (nsCOMPtr)aInput { nsAutoString keyStr; nsresult rv = aInput->GetKey(keyStr); if (NS_FAILED(rv)) { @@ -239,7 +244,8 @@ } + (NSTouchBarItemIdentifier)searchPopoverIdentifier { - return [TouchBarInput nativeIdentifierWithType:@"popover" withKey:@"search-popover"]; + return [TouchBarInput nativeIdentifierWithType:@"popover" + withKey:@"search-popover"]; } @end diff --git a/widget/cocoa/nsTouchBarInputIcon.mm b/widget/cocoa/nsTouchBarInputIcon.mm index ac9e907c8e1d..69e0c2aa0fc9 100644 --- a/widget/cocoa/nsTouchBarInputIcon.mm +++ b/widget/cocoa/nsTouchBarInputIcon.mm @@ -25,10 +25,16 @@ using mozilla::widget::IconLoader; static const uint32_t kIconHeight = 16; static const CGFloat kHiDPIScalingFactor = 2.0f; -nsTouchBarInputIcon::nsTouchBarInputIcon(RefPtr aDocument, TouchBarInput* aInput, +nsTouchBarInputIcon::nsTouchBarInputIcon(RefPtr aDocument, + TouchBarInput* aInput, NSTouchBarItem* aItem) - : mDocument(aDocument), mSetIcon(false), mButton(nil), mShareScrubber(nil), mPopoverItem(nil) { - if ([[aInput nativeIdentifier] isEqualToString:[TouchBarInput shareScrubberIdentifier]]) { + : mDocument(aDocument), + mSetIcon(false), + mButton(nil), + mShareScrubber(nil), + mPopoverItem(nil) { + if ([[aInput nativeIdentifier] + isEqualToString:[TouchBarInput shareScrubberIdentifier]]) { mShareScrubber = (NSSharingServicePickerTouchBarItem*)aItem; } else if ([aInput baseType] == TouchBarInputBaseType::kPopover) { mPopoverItem = (NSPopoverTouchBarItem*)aItem; @@ -89,10 +95,11 @@ nsresult nsTouchBarInputIcon::SetupIcon(nsCOMPtr aIconURI) { [mPopoverItem setCollapsedRepresentationImage:placeholder]; } - nsresult rv = mIconLoader->LoadIcon(aIconURI, mDocument, true /* aIsInternalIcon */); + nsresult rv = + mIconLoader->LoadIcon(aIconURI, mDocument, true /* aIsInternalIcon */); if (NS_FAILED(rv)) { - // There is no icon for this menu item, as an error occurred while loading it. - // An icon might have been set earlier or the place holder icon may have + // There is no icon for this menu item, as an error occurred while loading + // it. An icon might have been set earlier or the place holder icon may have // been set. Clear it. [mButton setImage:nil]; [mShareScrubber setButtonImage:nil]; @@ -117,11 +124,12 @@ nsresult nsTouchBarInputIcon::OnComplete(imgIContainer* aImage) { // We ask only for the HiDPI images since all Touch Bars are Retina // displays and we have no need for icons @1x. - NSImage* image = [MOZIconHelper iconImageFromImageContainer:aImage - withSize:NSMakeSize(kIconHeight, kIconHeight) - presContext:nullptr - computedStyle:nullptr - scaleFactor:kHiDPIScalingFactor]; + NSImage* image = [MOZIconHelper + iconImageFromImageContainer:aImage + withSize:NSMakeSize(kIconHeight, kIconHeight) + presContext:nullptr + computedStyle:nullptr + scaleFactor:kHiDPIScalingFactor]; [mButton setImage:image]; [mShareScrubber setButtonImage:image]; [mPopoverItem setCollapsedRepresentationImage:image]; diff --git a/widget/cocoa/nsTouchBarUpdater.mm b/widget/cocoa/nsTouchBarUpdater.mm index 6b4b25f992c3..0ecea8413bba 100644 --- a/widget/cocoa/nsTouchBarUpdater.mm +++ b/widget/cocoa/nsTouchBarUpdater.mm @@ -15,7 +15,8 @@ // defined in nsCocoaWindow.mm. extern BOOL sTouchBarIsInitialized; -#if !defined(MAC_OS_X_VERSION_10_12_2) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12_2 +#if !defined(MAC_OS_X_VERSION_10_12_2) || \ + MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12_2 @interface BaseWindow (NSTouchBarProvider) @property(strong) NSTouchBar* touchBar; @end @@ -24,8 +25,8 @@ extern BOOL sTouchBarIsInitialized; NS_IMPL_ISUPPORTS(nsTouchBarUpdater, nsITouchBarUpdater); NS_IMETHODIMP -nsTouchBarUpdater::UpdateTouchBarInputs(nsIBaseWindow* aWindow, - const nsTArray>& aInputs) { +nsTouchBarUpdater::UpdateTouchBarInputs( + nsIBaseWindow* aWindow, const nsTArray>& aInputs) { if (!sTouchBarIsInitialized || !aWindow) { return NS_OK; } @@ -43,15 +44,19 @@ nsTouchBarUpdater::UpdateTouchBarInputs(nsIBaseWindow* aWindow, continue; } - NSTouchBarItemIdentifier newIdentifier = [TouchBarInput nativeIdentifierWithXPCOM:input]; + NSTouchBarItemIdentifier newIdentifier = + [TouchBarInput nativeIdentifierWithXPCOM:input]; // We don't support updating the Share scrubber since it's a special // Apple-made component that behaves differently from the other inputs. - if ([newIdentifier isEqualToString:[TouchBarInput nativeIdentifierWithType:@"scrubber" - withKey:@"share"]]) { + if ([newIdentifier + isEqualToString:[TouchBarInput + nativeIdentifierWithType:@"scrubber" + withKey:@"share"]]) { continue; } - TouchBarInput* convertedInput = [[TouchBarInput alloc] initWithXPCOM:input]; + TouchBarInput* convertedInput = + [[TouchBarInput alloc] initWithXPCOM:input]; [(nsTouchBar*)cocoaWin.touchBar updateItem:convertedInput]; } } @@ -60,7 +65,8 @@ nsTouchBarUpdater::UpdateTouchBarInputs(nsIBaseWindow* aWindow, } NS_IMETHODIMP -nsTouchBarUpdater::ShowPopover(nsIBaseWindow* aWindow, nsITouchBarInput* aPopover, bool aShowing) { +nsTouchBarUpdater::ShowPopover(nsIBaseWindow* aWindow, + nsITouchBarInput* aPopover, bool aShowing) { if (!sTouchBarIsInitialized || !aPopover || !aWindow) { return NS_OK; } @@ -73,10 +79,12 @@ nsTouchBarUpdater::ShowPopover(nsIBaseWindow* aWindow, nsITouchBarInput* aPopove if ([cocoaWin respondsToSelector:@selector(touchBar)]) { // We don't need to completely reinitialize the popover. We only need its // identifier to look it up in [nsTouchBar mappedLayoutItems]. - NSTouchBarItemIdentifier popoverIdentifier = [TouchBarInput nativeIdentifierWithXPCOM:aPopover]; + NSTouchBarItemIdentifier popoverIdentifier = + [TouchBarInput nativeIdentifierWithXPCOM:aPopover]; TouchBarInput* popoverItem = - [[(nsTouchBar*)cocoaWin.touchBar mappedLayoutItems] objectForKey:popoverIdentifier]; + [[(nsTouchBar*)cocoaWin.touchBar mappedLayoutItems] + objectForKey:popoverIdentifier]; [(nsTouchBar*)cocoaWin.touchBar showPopover:popoverItem showing:aShowing]; } diff --git a/widget/cocoa/nsUserIdleServiceX.mm b/widget/cocoa/nsUserIdleServiceX.mm index bedaf0773b27..c3ae3f904fca 100644 --- a/widget/cocoa/nsUserIdleServiceX.mm +++ b/widget/cocoa/nsUserIdleServiceX.mm @@ -16,7 +16,8 @@ bool nsUserIdleServiceX::PollIdleTime(uint32_t* aIdleTime) { if (rval != KERN_SUCCESS) return false; io_iterator_t hidItr; - rval = IOServiceGetMatchingServices(masterPort, IOServiceMatching("IOHIDSystem"), &hidItr); + rval = IOServiceGetMatchingServices( + masterPort, IOServiceMatching("IOHIDSystem"), &hidItr); if (rval != KERN_SUCCESS) return false; NS_ASSERTION(hidItr, "Our iterator is null, but it ought not to be!"); @@ -27,14 +28,15 @@ bool nsUserIdleServiceX::PollIdleTime(uint32_t* aIdleTime) { IOObjectRelease(hidItr); NSMutableDictionary* hidProps; - rval = IORegistryEntryCreateCFProperties(entry, (CFMutableDictionaryRef*)&hidProps, - kCFAllocatorDefault, 0); + rval = IORegistryEntryCreateCFProperties( + entry, (CFMutableDictionaryRef*)&hidProps, kCFAllocatorDefault, 0); if (rval != KERN_SUCCESS) return false; NS_ASSERTION(hidProps, "HIDProperties is null, but no error was returned."); [hidProps autorelease]; id idleObj = [hidProps objectForKey:@"HIDIdleTime"]; - NS_ASSERTION([idleObj isKindOfClass:[NSData class]] || [idleObj isKindOfClass:[NSNumber class]], + NS_ASSERTION([idleObj isKindOfClass:[NSData class]] || + [idleObj isKindOfClass:[NSNumber class]], "What we got for the idle object is not what we expect!"); uint64_t time; diff --git a/widget/cocoa/nsWindowMap.mm b/widget/cocoa/nsWindowMap.mm index 2f6442400e07..5df8105bde06 100644 --- a/widget/cocoa/nsWindowMap.mm +++ b/widget/cocoa/nsWindowMap.mm @@ -62,7 +62,8 @@ if (!inWindow || [self dataForWindow:inWindow]) return; - TopLevelWindowData* windowData = [[TopLevelWindowData alloc] initWithWindow:inWindow]; + TopLevelWindowData* windowData = + [[TopLevelWindowData alloc] initWithWindow:inWindow]; [self setData:windowData forWindow:inWindow]; // takes ownership [windowData release]; @@ -114,30 +115,35 @@ NS_OBJC_BEGIN_TRY_BLOCK_RETURN; if ((self = [super init])) { - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(windowBecameKey:) - name:NSWindowDidBecomeKeyNotification - object:inWindow]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(windowBecameKey:) + name:NSWindowDidBecomeKeyNotification + object:inWindow]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(windowResignedKey:) - name:NSWindowDidResignKeyNotification - object:inWindow]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(windowResignedKey:) + name:NSWindowDidResignKeyNotification + object:inWindow]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(windowBecameMain:) - name:NSWindowDidBecomeMainNotification - object:inWindow]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(windowBecameMain:) + name:NSWindowDidBecomeMainNotification + object:inWindow]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(windowResignedMain:) - name:NSWindowDidResignMainNotification - object:inWindow]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(windowResignedMain:) + name:NSWindowDidResignMainNotification + object:inWindow]; - [[NSNotificationCenter defaultCenter] addObserver:self - selector:@selector(windowWillClose:) - name:NSWindowWillCloseNotification - object:inWindow]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(windowWillClose:) + name:NSWindowWillCloseNotification + object:inWindow]; } return self; @@ -200,7 +206,8 @@ NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; id firstResponder = [aWindow firstResponder]; - if ([firstResponder isKindOfClass:[ChildView class]]) [firstResponder viewsWindowDidBecomeKey]; + if ([firstResponder isKindOfClass:[ChildView class]]) + [firstResponder viewsWindowDidBecomeKey]; NS_OBJC_END_TRY_IGNORE_BLOCK; } @@ -211,7 +218,8 @@ NS_OBJC_BEGIN_TRY_IGNORE_BLOCK; id firstResponder = [aWindow firstResponder]; - if ([firstResponder isKindOfClass:[ChildView class]]) [firstResponder viewsWindowDidResignKey]; + if ([firstResponder isKindOfClass:[ChildView class]]) + [firstResponder viewsWindowDidResignKey]; NS_OBJC_END_TRY_IGNORE_BLOCK; } @@ -253,7 +261,8 @@ // Don't send events to a top-level window that has a sheet open above it -- // as far as Gecko is concerned, it's inactive, and stays so until the sheet // closes. - if (delegate && [delegate isKindOfClass:[WindowDelegate class]] && ![window attachedSheet]) + if (delegate && [delegate isKindOfClass:[WindowDelegate class]] && + ![window attachedSheet]) [TopLevelWindowData activateInWindow:window]; } @@ -261,7 +270,8 @@ NSWindow* window = (NSWindow*)[inNotification object]; id delegate = [window delegate]; - if (delegate && [delegate isKindOfClass:[WindowDelegate class]] && ![window attachedSheet]) + if (delegate && [delegate isKindOfClass:[WindowDelegate class]] && + ![window attachedSheet]) [TopLevelWindowData deactivateInWindow:window]; } @@ -272,7 +282,8 @@ [[self retain] autorelease]; // remove ourselves from the window map (which owns us) - [[WindowDataMap sharedWindowDataMap] removeDataForWindow:[inNotification object]]; + [[WindowDataMap sharedWindowDataMap] + removeDataForWindow:[inNotification object]]; NS_OBJC_END_TRY_IGNORE_BLOCK; } diff --git a/widget/headless/HeadlessKeyBindingsCocoa.mm b/widget/headless/HeadlessKeyBindingsCocoa.mm index 881bff50f43b..27ed07c461a6 100644 --- a/widget/headless/HeadlessKeyBindingsCocoa.mm +++ b/widget/headless/HeadlessKeyBindingsCocoa.mm @@ -24,24 +24,26 @@ HeadlessKeyBindings& HeadlessKeyBindings::GetInstance() { return *sInstance; } -nsresult HeadlessKeyBindings::AttachNativeKeyEvent(WidgetKeyboardEvent& aEvent) { +nsresult HeadlessKeyBindings::AttachNativeKeyEvent( + WidgetKeyboardEvent& aEvent) { NS_OBJC_BEGIN_TRY_BLOCK_RETURN; - aEvent.mNativeKeyEvent = nsCocoaUtils::MakeNewCococaEventFromWidgetEvent(aEvent, 0, nil); + aEvent.mNativeKeyEvent = + nsCocoaUtils::MakeNewCococaEventFromWidgetEvent(aEvent, 0, nil); return NS_OK; NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } -void HeadlessKeyBindings::GetEditCommands(NativeKeyBindingsType aType, - const WidgetKeyboardEvent& aEvent, - const Maybe& aWritingMode, - nsTArray& aCommands) { +void HeadlessKeyBindings::GetEditCommands( + NativeKeyBindingsType aType, const WidgetKeyboardEvent& aEvent, + const Maybe& aWritingMode, nsTArray& aCommands) { // Convert the widget keyboard into a cocoa event so it can be translated // into commands in the NativeKeyBindings. WidgetKeyboardEvent modifiedEvent(aEvent); - modifiedEvent.mNativeKeyEvent = nsCocoaUtils::MakeNewCococaEventFromWidgetEvent(aEvent, 0, nil); + modifiedEvent.mNativeKeyEvent = + nsCocoaUtils::MakeNewCococaEventFromWidgetEvent(aEvent, 0, nil); NativeKeyBindings* keyBindings = NativeKeyBindings::GetInstance(aType); keyBindings->GetEditCommands(modifiedEvent, aWritingMode, aCommands); diff --git a/widget/uikit/nsAppShell.mm b/widget/uikit/nsAppShell.mm index 1fd995f3e8ad..6324a04b4d0c 100644 --- a/widget/uikit/nsAppShell.mm +++ b/widget/uikit/nsAppShell.mm @@ -64,8 +64,8 @@ NSMutableArray* nsAppShell::gTopLevelViews = [[NSMutableArray alloc] init]; // We only create one window, since we can only display one window at // a time anyway. Also, iOS 4 fails to display UIWindows if you // create them before calling UIApplicationMain, so this makes more sense. - nsAppShell::gWindow = - [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] retain]; + nsAppShell::gWindow = [[[UIWindow alloc] + initWithFrame:[[UIScreen mainScreen] applicationFrame]] retain]; self.window = nsAppShell::gWindow; self.window.rootViewController = [[ViewController alloc] init]; @@ -119,7 +119,8 @@ nsAppShell::~nsAppShell() { if (mCFRunLoop) { if (mCFRunLoopSource) { - ::CFRunLoopRemoveSource(mCFRunLoop, mCFRunLoopSource, kCFRunLoopCommonModes); + ::CFRunLoopRemoveSource(mCFRunLoop, mCFRunLoopSource, + kCFRunLoopCommonModes); ::CFRelease(mCFRunLoopSource); } ::CFRelease(mCFRunLoop); @@ -212,7 +213,8 @@ bool nsAppShell::ProcessNextNativeEvent(bool aMayWait) { if (!currentMode) currentMode = NSDefaultRunLoopMode; if (aMayWait) - eventProcessed = [currentRunLoop runMode:currentMode beforeDate:waitUntil]; + eventProcessed = [currentRunLoop runMode:currentMode + beforeDate:waitUntil]; else [currentRunLoop acceptInputForMode:currentMode beforeDate:waitUntil]; } while (eventProcessed && aMayWait); diff --git a/widget/uikit/nsLookAndFeel.mm b/widget/uikit/nsLookAndFeel.mm index d1fa8db60cc3..29eb52a234e1 100644 --- a/widget/uikit/nsLookAndFeel.mm +++ b/widget/uikit/nsLookAndFeel.mm @@ -22,7 +22,8 @@ static nscolor GetColorFromUIColor(UIColor* aColor) { CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(cgColor)); const CGFloat* components = CGColorGetComponents(cgColor); if (model == kCGColorSpaceModelRGB) { - return NS_RGB((unsigned int)(components[0] * 255.0), (unsigned int)(components[1] * 255.0), + return NS_RGB((unsigned int)(components[0] * 255.0), + (unsigned int)(components[1] * 255.0), (unsigned int)(components[2] * 255.0)); } else if (model == kCGColorSpaceModelMonochrome) { unsigned int val = (unsigned int)(components[0] * 255.0); @@ -197,12 +198,13 @@ nsresult nsLookAndFeel::NativeGetColor(ColorID, ColorScheme, nscolor& aResult) { aResult = NS_TRANSPARENT; break; case ColorID::MozNativehyperlinktext: - // There appears to be no available system defined color. HARDCODING to the appropriate color. + // There appears to be no available system defined color. HARDCODING to + // the appropriate color. aResult = NS_RGB(0x14, 0x4F, 0xAE); break; case ColorID::MozNativevisitedhyperlinktext: - // Safari defaults to the MacOS color implementation for visited links, which in turn uses - // systemPurpleColor, so we do the same here. + // Safari defaults to the MacOS color implementation for visited links, + // which in turn uses systemPurpleColor, so we do the same here. aResult = GetColorFromUIColor([UIColor systemPurpleColor]); break; default: @@ -321,7 +323,8 @@ nsLookAndFeel::NativeGetFloat(FloatID aID, float& aResult) { return res; } -bool nsLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName, gfxFontStyle& aFontStyle) { +bool nsLookAndFeel::NativeGetFont(FontID aID, nsString& aFontName, + gfxFontStyle& aFontStyle) { // hack for now if (aID == FontID::Window || aID == FontID::Document) { aFontStyle.style = FontSlantStyle::Normal(); diff --git a/widget/uikit/nsScreenManager.mm b/widget/uikit/nsScreenManager.mm index a9ed0f3d6693..da37a4199d88 100644 --- a/widget/uikit/nsScreenManager.mm +++ b/widget/uikit/nsScreenManager.mm @@ -15,12 +15,14 @@ static bool gScreenBoundsSet = false; UIKitScreen::UIKitScreen(UIScreen* aScreen) { mScreen = [aScreen retain]; } NS_IMETHODIMP -UIKitScreen::GetRect(int32_t* outX, int32_t* outY, int32_t* outWidth, int32_t* outHeight) { +UIKitScreen::GetRect(int32_t* outX, int32_t* outY, int32_t* outWidth, + int32_t* outHeight) { return GetRectDisplayPix(outX, outY, outWidth, outHeight); } NS_IMETHODIMP -UIKitScreen::GetAvailRect(int32_t* outX, int32_t* outY, int32_t* outWidth, int32_t* outHeight) { +UIKitScreen::GetAvailRect(int32_t* outX, int32_t* outY, int32_t* outWidth, + int32_t* outHeight) { return GetAvailRectDisplayPix(outX, outY, outWidth, outHeight); } @@ -37,8 +39,8 @@ UIKitScreen::GetRectDisplayPix(int32_t* outX, int32_t* outY, int32_t* outWidth, } NS_IMETHODIMP -UIKitScreen::GetAvailRectDisplayPix(int32_t* outX, int32_t* outY, int32_t* outWidth, - int32_t* outHeight) { +UIKitScreen::GetAvailRectDisplayPix(int32_t* outX, int32_t* outY, + int32_t* outWidth, int32_t* outHeight) { CGRect rect = [mScreen applicationFrame]; CGFloat scale = [mScreen scale]; @@ -58,7 +60,9 @@ UIKitScreen::GetPixelDepth(int32_t* aPixelDepth) { } NS_IMETHODIMP -UIKitScreen::GetColorDepth(int32_t* aColorDepth) { return GetPixelDepth(aColorDepth); } +UIKitScreen::GetColorDepth(int32_t* aColorDepth) { + return GetPixelDepth(aColorDepth); +} NS_IMETHODIMP UIKitScreen::GetContentsScaleFactor(double* aContentsScaleFactor) { @@ -68,7 +72,8 @@ UIKitScreen::GetContentsScaleFactor(double* aContentsScaleFactor) { NS_IMPL_ISUPPORTS(UIKitScreenManager, nsIScreenManager) -UIKitScreenManager::UIKitScreenManager() : mScreen(new UIKitScreen([UIScreen mainScreen])) {} +UIKitScreenManager::UIKitScreenManager() + : mScreen(new UIKitScreen([UIScreen mainScreen])) {} LayoutDeviceIntRect UIKitScreenManager::GetBounds() { if (!gScreenBoundsSet) { @@ -80,8 +85,8 @@ LayoutDeviceIntRect UIKitScreenManager::GetBounds() { gScreenBounds.height = rect.size.height * scale; gScreenBoundsSet = true; } - printf("UIKitScreenManager::GetBounds: %d %d %d %d\n", gScreenBounds.x, gScreenBounds.y, - gScreenBounds.width, gScreenBounds.height); + printf("UIKitScreenManager::GetBounds: %d %d %d %d\n", gScreenBounds.x, + gScreenBounds.y, gScreenBounds.width, gScreenBounds.height); return gScreenBounds; } @@ -92,7 +97,8 @@ UIKitScreenManager::GetPrimaryScreen(nsIScreen** outScreen) { } NS_IMETHODIMP -UIKitScreenManager::ScreenForRect(int32_t inLeft, int32_t inTop, int32_t inWidth, int32_t inHeight, +UIKitScreenManager::ScreenForRect(int32_t inLeft, int32_t inTop, + int32_t inWidth, int32_t inHeight, nsIScreen** outScreen) { return GetPrimaryScreen(outScreen); } diff --git a/widget/uikit/nsWidgetFactory.mm b/widget/uikit/nsWidgetFactory.mm index 7250d6ddad13..356e5b8cdf83 100644 --- a/widget/uikit/nsWidgetFactory.mm +++ b/widget/uikit/nsWidgetFactory.mm @@ -44,6 +44,10 @@ static void nsWidgetUIKitModuleDtor() { nsAppShellShutdown(); } -extern const mozilla::Module kWidgetModule = { - mozilla::Module::kVersion, kWidgetCIDs, kWidgetContracts, nullptr, nullptr, nsAppShellInit, - nsWidgetUIKitModuleDtor}; +extern const mozilla::Module kWidgetModule = {mozilla::Module::kVersion, + kWidgetCIDs, + kWidgetContracts, + nullptr, + nullptr, + nsAppShellInit, + nsWidgetUIKitModuleDtor}; diff --git a/widget/uikit/nsWindow.mm b/widget/uikit/nsWindow.mm index ba360f928e4e..0c1a38c27c71 100644 --- a/widget/uikit/nsWindow.mm +++ b/widget/uikit/nsWindow.mm @@ -45,14 +45,18 @@ using namespace mozilla::layers; fprintf(stderr, args); \ fprintf(stderr, "\n") -static LayoutDeviceIntPoint UIKitPointsToDevPixels(CGPoint aPoint, CGFloat aBackingScale) { +static LayoutDeviceIntPoint UIKitPointsToDevPixels(CGPoint aPoint, + CGFloat aBackingScale) { return LayoutDeviceIntPoint(NSToIntRound(aPoint.x * aBackingScale), NSToIntRound(aPoint.y * aBackingScale)); } -static CGRect DevPixelsToUIKitPoints(const LayoutDeviceIntRect& aRect, CGFloat aBackingScale) { - return CGRectMake((CGFloat)aRect.x / aBackingScale, (CGFloat)aRect.y / aBackingScale, - (CGFloat)aRect.width / aBackingScale, (CGFloat)aRect.height / aBackingScale); +static CGRect DevPixelsToUIKitPoints(const LayoutDeviceIntRect& aRect, + CGFloat aBackingScale) { + return CGRectMake((CGFloat)aRect.x / aBackingScale, + (CGFloat)aRect.y / aBackingScale, + (CGFloat)aRect.width / aBackingScale, + (CGFloat)aRect.height / aBackingScale); } // Used to retain a Cocoa object for the remainder of a method's execution. @@ -85,7 +89,9 @@ class nsAutoRetainUIKitObject { - (BOOL)isUsingMainThreadOpenGL; - (void)drawUsingOpenGL; - (void)drawUsingOpenGLCallback; -- (void)sendTouchEvent:(EventMessage)aType touches:(NSSet*)aTouches widget:(nsWindow*)aWindow; +- (void)sendTouchEvent:(EventMessage)aType + touches:(NSSet*)aTouches + widget:(nsWindow*)aWindow; // Event handling (UIResponder) - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event; - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event; @@ -103,16 +109,19 @@ class nsAutoRetainUIKitObject { if ((self = [super initWithFrame:inFrame])) { mGeckoChild = inChild; } - ALOG("[ChildView[%p] initWithFrame:] (mGeckoChild = %p)", (void*)self, (void*)mGeckoChild); + ALOG("[ChildView[%p] initWithFrame:] (mGeckoChild = %p)", (void*)self, + (void*)mGeckoChild); self.opaque = YES; self.alpha = 1.0; UITapGestureRecognizer* tapRecognizer = - [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; + [[UITapGestureRecognizer alloc] initWithTarget:self + action:@selector(handleTap:)]; tapRecognizer.numberOfTapsRequired = 1; [self addGestureRecognizer:tapRecognizer]; - mTouches = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr); + mTouches = + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr); mNextTouchID = 0; return self; } @@ -130,7 +139,8 @@ class nsAutoRetainUIKitObject { - (void)sendMouseEvent:(EventMessage)aType point:(LayoutDeviceIntPoint)aPoint widget:(nsWindow*)aWindow { - WidgetMouseEvent event(true, aType, aWindow, WidgetMouseEvent::eReal, WidgetMouseEvent::eNormal); + WidgetMouseEvent event(true, aType, aWindow, WidgetMouseEvent::eReal, + WidgetMouseEvent::eNormal); event.mRefPoint = aPoint; event.mClickCount = 1; @@ -145,24 +155,27 @@ class nsAutoRetainUIKitObject { - (void)handleTap:(UITapGestureRecognizer*)sender { if (sender.state == UIGestureRecognizerStateEnded) { ALOG("[ChildView[%p] handleTap]", self); - LayoutDeviceIntPoint lp = - UIKitPointsToDevPixels([sender locationInView:self], [self contentScaleFactor]); + LayoutDeviceIntPoint lp = UIKitPointsToDevPixels( + [sender locationInView:self], [self contentScaleFactor]); [self sendMouseEvent:eMouseMove point:lp widget:mGeckoChild]; [self sendMouseEvent:eMouseDown point:lp widget:mGeckoChild]; [self sendMouseEvent:eMouseUp point:lp widget:mGeckoChild]; } } -- (void)sendTouchEvent:(EventMessage)aType touches:(NSSet*)aTouches widget:(nsWindow*)aWindow { +- (void)sendTouchEvent:(EventMessage)aType + touches:(NSSet*)aTouches + widget:(nsWindow*)aWindow { WidgetTouchEvent event(true, aType, aWindow); // XXX: I think nativeEvent.timestamp * 1000 is probably usable here but // I don't care that much right now. event.mTime = PR_IntervalNow(); event.mTouches.SetCapacity(aTouches.count); for (UITouch* touch in aTouches) { - LayoutDeviceIntPoint loc = - UIKitPointsToDevPixels([touch locationInView:self], [self contentScaleFactor]); - LayoutDeviceIntPoint radius = UIKitPointsToDevPixels([touch majorRadius], [touch majorRadius]); + LayoutDeviceIntPoint loc = UIKitPointsToDevPixels( + [touch locationInView:self], [self contentScaleFactor]); + LayoutDeviceIntPoint radius = + UIKitPointsToDevPixels([touch majorRadius], [touch majorRadius]); void* value; if (!CFDictionaryGetValueIfPresent(mTouches, touch, (const void**)&value)) { // This shouldn't happen. @@ -185,7 +198,9 @@ class nsAutoRetainUIKitObject { CFDictionaryAddValue(mTouches, touch, (void*)mNextTouchID); mNextTouchID++; } - [self sendTouchEvent:eTouchStart touches:[event allTouches] widget:mGeckoChild]; + [self sendTouchEvent:eTouchStart + touches:[event allTouches] + widget:mGeckoChild]; } - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { @@ -216,7 +231,9 @@ class nsAutoRetainUIKitObject { ALOG("[ChildView[%p] touchesMoved", self); if (!mGeckoChild) return; - [self sendTouchEvent:eTouchMove touches:[event allTouches] widget:mGeckoChild]; + [self sendTouchEvent:eTouchMove + touches:[event allTouches] + widget:mGeckoChild]; } - (void)setNeedsDisplayInRect:(CGRect)aRect { @@ -275,13 +292,16 @@ class nsAutoRetainUIKitObject { #ifdef DEBUG_UPDATE LayoutDeviceIntRect geckoBounds = mGeckoChild->GetBounds(); - fprintf(stderr, "---- Update[%p][%p] [%f %f %f %f] cgc: %p\n gecko bounds: [%d %d %d %d]\n", - self, mGeckoChild, aRect.origin.x, aRect.origin.y, aRect.size.width, aRect.size.height, - aContext, geckoBounds.x, geckoBounds.y, geckoBounds.width, geckoBounds.height); + fprintf(stderr, + "---- Update[%p][%p] [%f %f %f %f] cgc: %p\n gecko bounds: [%d %d " + "%d %d]\n", + self, mGeckoChild, aRect.origin.x, aRect.origin.y, aRect.size.width, + aRect.size.height, aContext, geckoBounds.x, geckoBounds.y, + geckoBounds.width, geckoBounds.height); CGAffineTransform xform = CGContextGetCTM(aContext); - fprintf(stderr, " xform in: [%f %f %f %f %f %f]\n", xform.a, xform.b, xform.c, xform.d, xform.tx, - xform.ty); + fprintf(stderr, " xform in: [%f %f %f %f %f %f]\n", xform.a, xform.b, + xform.c, xform.d, xform.tx, xform.ty); #endif if (true) { @@ -310,15 +330,18 @@ class nsAutoRetainUIKitObject { CGContextSaveGState(aContext); - LayoutDeviceIntRegion region = LayoutDeviceIntRect( - NSToIntRound(aRect.origin.x * scale), NSToIntRound(aRect.origin.y * scale), - NSToIntRound(aRect.size.width * scale), NSToIntRound(aRect.size.height * scale)); + LayoutDeviceIntRegion region = + LayoutDeviceIntRect(NSToIntRound(aRect.origin.x * scale), + NSToIntRound(aRect.origin.y * scale), + NSToIntRound(aRect.size.width * scale), + NSToIntRound(aRect.size.height * scale)); // Create Cairo objects. RefPtr targetSurface; UniquePtrPtr targetContext; - if (gfxPlatform::GetPlatform()->SupportsAzureContentForType(gfx::BackendType::CAIRO)) { + if (gfxPlatform::GetPlatform()->SupportsAzureContentForType( + gfx::BackendType::CAIRO)) { // This is dead code unless you mess with prefs, but keep it around for // debugging. targetSurface = new gfxQuartzSurface(aContext, backingSize); @@ -379,7 +402,10 @@ class nsAutoRetainUIKitObject { @end nsWindow::nsWindow() - : mNativeView(nullptr), mVisible(false), mSizeMode(nsSizeMode_Normal), mParent(nullptr) {} + : mNativeView(nullptr), + mVisible(false), + mSizeMode(nsSizeMode_Normal), + mParent(nullptr) {} nsWindow::~nsWindow() { [mNativeView widgetDestroyed]; // Safe if mNativeView is nil. @@ -396,7 +422,8 @@ void nsWindow::TearDownView() { } bool nsWindow::IsTopLevel() { - return mWindowType == WindowType::TopLevel || mWindowType == WindowType::Dialog || + return mWindowType == WindowType::TopLevel || + mWindowType == WindowType::Dialog || mWindowType == WindowType::Invisible; } @@ -405,7 +432,8 @@ bool nsWindow::IsTopLevel() { // nsresult nsWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent, - const LayoutDeviceIntRect& aRect, widget::InitData* aInitData) { + const LayoutDeviceIntRect& aRect, + widget::InitData* aInitData) { ALOG("nsWindow[%p]::Create %p/%p [%d %d %d %d]", (void*)this, (void*)aParent, (void*)aNativeParent, aRect.x, aRect.y, aRect.width, aRect.height); nsWindow* parent = (nsWindow*)aParent; @@ -429,8 +457,8 @@ nsresult nsWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent, mBounds = aRect; } - ALOG("nsWindow[%p]::Create bounds: %d %d %d %d", (void*)this, mBounds.x, mBounds.y, mBounds.width, - mBounds.height); + ALOG("nsWindow[%p]::Create bounds: %d %d %d %d", (void*)this, mBounds.x, + mBounds.y, mBounds.width, mBounds.height); // Set defaults which can be overriden from aInitData in BaseCreate mWindowType = WindowType::TopLevel; @@ -438,11 +466,12 @@ nsresult nsWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent, Inherited::BaseCreate(aParent, aInitData); - NS_ASSERTION(IsTopLevel() || parent, "non top level window doesn't have a parent!"); + NS_ASSERTION(IsTopLevel() || parent, + "non top level window doesn't have a parent!"); - mNativeView = - [[ChildView alloc] initWithFrame:DevPixelsToUIKitPoints(mBounds, BackingScaleFactor()) - geckoChild:this]; + mNativeView = [[ChildView alloc] + initWithFrame:DevPixelsToUIKitPoints(mBounds, BackingScaleFactor()) + geckoChild:this]; mNativeView.hidden = YES; if (parent) { @@ -486,8 +515,9 @@ void nsWindow::Show(bool aState) { if (aState != mVisible) { mNativeView.hidden = aState ? NO : YES; if (aState) { - UIView* parentView = - mParent ? mParent->mNativeView : nsAppShell::gWindow.rootViewController.view; + UIView* parentView = mParent + ? mParent->mNativeView + : nsAppShell::gWindow.rootViewController.view; [parentView bringSubviewToFront:mNativeView]; [mNativeView setNeedsDisplay]; } @@ -511,7 +541,8 @@ void nsWindow::Move(double aX, double aY) { ReportMoveEvent(); } -void nsWindow::Resize(double aX, double aY, double aWidth, double aHeight, bool aRepaint) { +void nsWindow::Resize(double aX, double aY, double aWidth, double aHeight, + bool aRepaint) { BOOL isMoving = (mBounds.x != aX || mBounds.y != aY); BOOL isResizing = (mBounds.width != aWidth || mBounds.height != aHeight); if (!mNativeView || (!isMoving && !isResizing)) return; @@ -535,7 +566,8 @@ void nsWindow::Resize(double aX, double aY, double aWidth, double aHeight, bool } void nsWindow::Resize(double aWidth, double aHeight, bool aRepaint) { - if (!mNativeView || (mBounds.width == aWidth && mBounds.height == aHeight)) return; + if (!mNativeView || (mBounds.width == aWidth && mBounds.height == aHeight)) + return; mBounds.width = aWidth; mBounds.height = aHeight; @@ -563,11 +595,13 @@ void nsWindow::SetSizeMode(nsSizeMode aMode) { void nsWindow::Invalidate(const LayoutDeviceIntRect& aRect) { if (!mNativeView || !mVisible) return; - MOZ_RELEASE_ASSERT(GetLayerManager()->GetBackendType() != LayersBackend::LAYERS_WR, - "Shouldn't need to invalidate with accelerated OMTC layers!"); + MOZ_RELEASE_ASSERT( + GetLayerManager()->GetBackendType() != LayersBackend::LAYERS_WR, + "Shouldn't need to invalidate with accelerated OMTC layers!"); [mNativeView setNeedsLayout]; - [mNativeView setNeedsDisplayInRect:DevPixelsToUIKitPoints(mBounds, BackingScaleFactor())]; + [mNativeView setNeedsDisplayInRect:DevPixelsToUIKitPoints( + mBounds, BackingScaleFactor())]; } void nsWindow::SetFocus(Raise) { @@ -644,21 +678,26 @@ LayoutDeviceIntPoint nsWindow::WidgetToScreenOffset() { return offset; } -nsresult nsWindow::DispatchEvent(mozilla::WidgetGUIEvent* aEvent, nsEventStatus& aStatus) { +nsresult nsWindow::DispatchEvent(mozilla::WidgetGUIEvent* aEvent, + nsEventStatus& aStatus) { aStatus = nsEventStatus_eIgnore; nsCOMPtr kungFuDeathGrip(aEvent->mWidget); - if (mWidgetListener) aStatus = mWidgetListener->HandleEvent(aEvent, mUseAttachedEvents); + if (mWidgetListener) + aStatus = mWidgetListener->HandleEvent(aEvent, mUseAttachedEvents); return NS_OK; } -void nsWindow::SetInputContext(const InputContext& aContext, const InputContextAction& aAction) { +void nsWindow::SetInputContext(const InputContext& aContext, + const InputContextAction& aAction) { // TODO: actually show VKB mInputContext = aContext; } -mozilla::widget::InputContext nsWindow::GetInputContext() { return mInputContext; } +mozilla::widget::InputContext nsWindow::GetInputContext() { + return mInputContext; +} void nsWindow::SetBackgroundColor(const nscolor& aColor) { mNativeView.backgroundColor = [UIColor colorWithRed:NS_GET_R(aColor) diff --git a/xpcom/base/MacHelpers.mm b/xpcom/base/MacHelpers.mm index 22d8ef61a498..26c04c49dd4f 100644 --- a/xpcom/base/MacHelpers.mm +++ b/xpcom/base/MacHelpers.mm @@ -24,7 +24,8 @@ nsresult GetSelectedCityInfo(nsAString& aCountryCode) { return NS_ERROR_FAILURE; } - return mozilla::CopyCocoaStringToXPCOMString((NSString*)countryCode, aCountryCode); + return mozilla::CopyCocoaStringToXPCOMString((NSString*)countryCode, + aCountryCode); NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE); } diff --git a/xpcom/base/MacStringHelpers.mm b/xpcom/base/MacStringHelpers.mm index 9bfbdd912e9d..cf0b03665d19 100644 --- a/xpcom/base/MacStringHelpers.mm +++ b/xpcom/base/MacStringHelpers.mm @@ -24,7 +24,8 @@ nsresult CopyCocoaStringToXPCOMString(NSString* aFrom, nsAString& aTo) { return NS_ERROR_OUT_OF_MEMORY; } - [aFrom getCharacters:reinterpret_cast(aTo.BeginWriting()) range:NSMakeRange(0, len)]; + [aFrom getCharacters:reinterpret_cast(aTo.BeginWriting()) + range:NSMakeRange(0, len)]; return NS_OK; diff --git a/xpcom/base/nsMacPreferencesReader.mm b/xpcom/base/nsMacPreferencesReader.mm index ad9a59a9f442..bfec81cd8542 100644 --- a/xpcom/base/nsMacPreferencesReader.mm +++ b/xpcom/base/nsMacPreferencesReader.mm @@ -15,7 +15,8 @@ NS_IMPL_ISUPPORTS(nsMacPreferencesReader, nsIMacPreferencesReader) using namespace mozilla; -static void EvaluateDict(JSONWriter* aWriter, NSDictionary* aDict); +static void EvaluateDict(JSONWriter* aWriter, + NSDictionary* aDict); static void EvaluateArray(JSONWriter* aWriter, NSArray* aArray) { for (id elem in aArray) { @@ -35,13 +36,16 @@ static void EvaluateArray(JSONWriter* aWriter, NSArray* aArray) { } } -static void EvaluateDict(JSONWriter* aWriter, NSDictionary* aDict) { +static void EvaluateDict(JSONWriter* aWriter, + NSDictionary* aDict) { for (NSString* key in aDict) { id value = aDict[key]; if ([value isKindOfClass:[NSString class]]) { - aWriter->StringProperty(MakeStringSpan([key UTF8String]), MakeStringSpan([value UTF8String])); + aWriter->StringProperty(MakeStringSpan([key UTF8String]), + MakeStringSpan([value UTF8String])); } else if ([value isKindOfClass:[NSNumber class]]) { - aWriter->IntProperty(MakeStringSpan([key UTF8String]), [value longLongValue]); + aWriter->IntProperty(MakeStringSpan([key UTF8String]), + [value longLongValue]); } else if ([value isKindOfClass:[NSArray class]]) { aWriter->StartArrayProperty(MakeStringSpan([key UTF8String])); EvaluateArray(aWriter, value); @@ -56,17 +60,21 @@ static void EvaluateDict(JSONWriter* aWriter, NSDictionary* aDict NS_IMETHODIMP nsMacPreferencesReader::PoliciesEnabled(bool* aPoliciesEnabled) { - NSString* policiesEnabledStr = [NSString stringWithUTF8String:ENTERPRISE_POLICIES_ENABLED_KEY]; - *aPoliciesEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:policiesEnabledStr] == YES; + NSString* policiesEnabledStr = + [NSString stringWithUTF8String:ENTERPRISE_POLICIES_ENABLED_KEY]; + *aPoliciesEnabled = [[NSUserDefaults standardUserDefaults] + boolForKey:policiesEnabledStr] == YES; return NS_OK; } NS_IMETHODIMP -nsMacPreferencesReader::ReadPreferences(JSContext* aCx, JS::MutableHandle aResult) { +nsMacPreferencesReader::ReadPreferences(JSContext* aCx, + JS::MutableHandle aResult) { JSONStringWriteFunc jsonStr; JSONWriter w(jsonStr); w.Start(); - EvaluateDict(&w, [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]); + EvaluateDict( + &w, [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]); w.End(); NS_ConvertUTF8toUTF16 jsonStr16(jsonStr.StringCRef()); diff --git a/xpcom/base/nsObjCExceptions.mm b/xpcom/base/nsObjCExceptions.mm index 9921c746a100..77a7edc9980e 100644 --- a/xpcom/base/nsObjCExceptions.mm +++ b/xpcom/base/nsObjCExceptions.mm @@ -18,12 +18,15 @@ #include "nsError.h" void nsObjCExceptionLog(NSException* aException) { - NSLog(@"Mozilla has caught an Obj-C exception [%@: %@]", [aException name], [aException reason]); + NSLog(@"Mozilla has caught an Obj-C exception [%@: %@]", [aException name], + [aException reason]); // Attach exception info to the crash report. - nsCOMPtr crashReporter = do_GetService("@mozilla.org/toolkit/crash-reporter;1"); + nsCOMPtr crashReporter = + do_GetService("@mozilla.org/toolkit/crash-reporter;1"); if (crashReporter) { - crashReporter->AppendObjCExceptionInfoToAppNotes(static_cast(aException)); + crashReporter->AppendObjCExceptionInfoToAppNotes( + static_cast(aException)); } #ifdef DEBUG @@ -34,8 +37,8 @@ void nsObjCExceptionLog(NSException* aException) { namespace mozilla { bool ShouldIgnoreObjCException(NSException* aException) { - // Ignore known exceptions that we've seen in crash reports, which shouldn't cause a MOZ_CRASH in - // Nightly. + // Ignore known exceptions that we've seen in crash reports, which shouldn't + // cause a MOZ_CRASH in Nightly. if (aException.name == NSInternalInconsistencyException) { if ([aException.reason containsString:@"Missing Touches."]) { // Seen in bug 1694000. diff --git a/xpcom/io/CocoaFileUtils.mm b/xpcom/io/CocoaFileUtils.mm index 01e943064f75..9665358ac9ee 100644 --- a/xpcom/io/CocoaFileUtils.mm +++ b/xpcom/io/CocoaFileUtils.mm @@ -55,8 +55,9 @@ nsresult GetFileCreatorCode(CFURLRef url, OSType* creatorCode) { return NS_ERROR_FAILURE; } - NSDictionary* dict = [[NSFileManager defaultManager] attributesOfItemAtPath:resolvedPath - error:nil]; + NSDictionary* dict = + [[NSFileManager defaultManager] attributesOfItemAtPath:resolvedPath + error:nil]; if (!dict) { return NS_ERROR_FAILURE; } @@ -78,12 +79,13 @@ nsresult SetFileCreatorCode(CFURLRef url, OSType creatorCode) { if (NS_WARN_IF(!url)) return NS_ERROR_INVALID_ARG; NSAutoreleasePool* ap = [[NSAutoreleasePool alloc] init]; - NSDictionary* dict = - [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedLong:creatorCode] - forKey:NSFileHFSCreatorCode]; - BOOL success = [[NSFileManager defaultManager] setAttributes:dict - ofItemAtPath:[(NSURL*)url path] - error:nil]; + NSDictionary* dict = [NSDictionary + dictionaryWithObject:[NSNumber numberWithUnsignedLong:creatorCode] + forKey:NSFileHFSCreatorCode]; + BOOL success = + [[NSFileManager defaultManager] setAttributes:dict + ofItemAtPath:[(NSURL*)url path] + error:nil]; [ap release]; return (success ? NS_OK : NS_ERROR_FAILURE); @@ -102,8 +104,9 @@ nsresult GetFileTypeCode(CFURLRef url, OSType* typeCode) { return NS_ERROR_FAILURE; } - NSDictionary* dict = [[NSFileManager defaultManager] attributesOfItemAtPath:resolvedPath - error:nil]; + NSDictionary* dict = + [[NSFileManager defaultManager] attributesOfItemAtPath:resolvedPath + error:nil]; if (!dict) { return NS_ERROR_FAILURE; } @@ -125,11 +128,13 @@ nsresult SetFileTypeCode(CFURLRef url, OSType typeCode) { if (NS_WARN_IF(!url)) return NS_ERROR_INVALID_ARG; NSAutoreleasePool* ap = [[NSAutoreleasePool alloc] init]; - NSDictionary* dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedLong:typeCode] - forKey:NSFileHFSTypeCode]; - BOOL success = [[NSFileManager defaultManager] setAttributes:dict - ofItemAtPath:[(NSURL*)url path] - error:nil]; + NSDictionary* dict = [NSDictionary + dictionaryWithObject:[NSNumber numberWithUnsignedLong:typeCode] + forKey:NSFileHFSTypeCode]; + BOOL success = + [[NSFileManager defaultManager] setAttributes:dict + ofItemAtPath:[(NSURL*)url path] + error:nil]; [ap release]; return (success ? NS_OK : NS_ERROR_FAILURE); @@ -137,22 +142,26 @@ nsresult SetFileTypeCode(CFURLRef url, OSType typeCode) { } // Can be called off of the main thread. -void AddOriginMetadataToFile(const CFStringRef filePath, const CFURLRef sourceURL, +void AddOriginMetadataToFile(const CFStringRef filePath, + const CFURLRef sourceURL, const CFURLRef referrerURL) { - typedef OSStatus (*MDItemSetAttribute_type)(MDItemRef, CFStringRef, CFTypeRef); + typedef OSStatus (*MDItemSetAttribute_type)(MDItemRef, CFStringRef, + CFTypeRef); static MDItemSetAttribute_type mdItemSetAttributeFunc = NULL; static bool did_symbol_lookup = false; if (!did_symbol_lookup) { did_symbol_lookup = true; - CFBundleRef metadata_bundle = ::CFBundleGetBundleWithIdentifier(CFSTR("com.apple.Metadata")); + CFBundleRef metadata_bundle = + ::CFBundleGetBundleWithIdentifier(CFSTR("com.apple.Metadata")); if (!metadata_bundle) { return; } - mdItemSetAttributeFunc = (MDItemSetAttribute_type)::CFBundleGetFunctionPointerForName( - metadata_bundle, CFSTR("MDItemSetAttribute")); + mdItemSetAttributeFunc = + (MDItemSetAttribute_type)::CFBundleGetFunctionPointerForName( + metadata_bundle, CFSTR("MDItemSetAttribute")); } if (!mdItemSetAttributeFunc) { return; @@ -186,15 +195,16 @@ void AddOriginMetadataToFile(const CFStringRef filePath, const CFURLRef sourceUR } // Can be called off of the main thread. -static CFMutableDictionaryRef CreateQuarantineDictionary(const CFURLRef aFileURL, - const bool aCreateProps) { +static CFMutableDictionaryRef CreateQuarantineDictionary( + const CFURLRef aFileURL, const bool aCreateProps) { CFDictionaryRef quarantineProps = NULL; if (aCreateProps) { - quarantineProps = ::CFDictionaryCreate(NULL, NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, + quarantineProps = ::CFDictionaryCreate(NULL, NULL, NULL, 0, + &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } else { - Boolean success = ::CFURLCopyResourcePropertyForKey(aFileURL, kCFURLQuarantinePropertiesKey, - &quarantineProps, NULL); + Boolean success = ::CFURLCopyResourcePropertyForKey( + aFileURL, kCFURLQuarantinePropertiesKey, &quarantineProps, NULL); // If there aren't any quarantine properties then the user probably // set up an exclusion and we don't need to add metadata. if (!success || !quarantineProps) { @@ -209,21 +219,24 @@ static CFMutableDictionaryRef CreateQuarantineDictionary(const CFURLRef aFileURL } // Make a mutable copy of the properties. - CFMutableDictionaryRef mutQuarantineProps = - ::CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, (CFDictionaryRef)quarantineProps); + CFMutableDictionaryRef mutQuarantineProps = ::CFDictionaryCreateMutableCopy( + kCFAllocatorDefault, 0, (CFDictionaryRef)quarantineProps); ::CFRelease(quarantineProps); return mutQuarantineProps; } // Can be called off of the main thread. -void AddQuarantineMetadataToFile(const CFStringRef filePath, const CFURLRef sourceURL, - const CFURLRef referrerURL, const bool isFromWeb, +void AddQuarantineMetadataToFile(const CFStringRef filePath, + const CFURLRef sourceURL, + const CFURLRef referrerURL, + const bool isFromWeb, const bool createProps /* = false */) { - CFURLRef fileURL = - ::CFURLCreateWithFileSystemPath(kCFAllocatorDefault, filePath, kCFURLPOSIXPathStyle, false); + CFURLRef fileURL = ::CFURLCreateWithFileSystemPath( + kCFAllocatorDefault, filePath, kCFURLPOSIXPathStyle, false); - CFMutableDictionaryRef mutQuarantineProps = CreateQuarantineDictionary(fileURL, createProps); + CFMutableDictionaryRef mutQuarantineProps = + CreateQuarantineDictionary(fileURL, createProps); if (!mutQuarantineProps) { ::CFRelease(fileURL); return; @@ -232,42 +245,51 @@ void AddQuarantineMetadataToFile(const CFStringRef filePath, const CFURLRef sour // Add metadata that the OS couldn't infer. if (!::CFDictionaryGetValue(mutQuarantineProps, kLSQuarantineTypeKey)) { - CFStringRef type = isFromWeb ? kLSQuarantineTypeWebDownload : kLSQuarantineTypeOtherDownload; + CFStringRef type = isFromWeb ? kLSQuarantineTypeWebDownload + : kLSQuarantineTypeOtherDownload; ::CFDictionarySetValue(mutQuarantineProps, kLSQuarantineTypeKey, type); } - if (!::CFDictionaryGetValue(mutQuarantineProps, kLSQuarantineOriginURLKey) && referrerURL) { - ::CFDictionarySetValue(mutQuarantineProps, kLSQuarantineOriginURLKey, referrerURL); + if (!::CFDictionaryGetValue(mutQuarantineProps, kLSQuarantineOriginURLKey) && + referrerURL) { + ::CFDictionarySetValue(mutQuarantineProps, kLSQuarantineOriginURLKey, + referrerURL); } - if (!::CFDictionaryGetValue(mutQuarantineProps, kLSQuarantineDataURLKey) && sourceURL) { - ::CFDictionarySetValue(mutQuarantineProps, kLSQuarantineDataURLKey, sourceURL); + if (!::CFDictionaryGetValue(mutQuarantineProps, kLSQuarantineDataURLKey) && + sourceURL) { + ::CFDictionarySetValue(mutQuarantineProps, kLSQuarantineDataURLKey, + sourceURL); } // Set quarantine properties on file. - ::CFURLSetResourcePropertyForKey(fileURL, kCFURLQuarantinePropertiesKey, mutQuarantineProps, - NULL); + ::CFURLSetResourcePropertyForKey(fileURL, kCFURLQuarantinePropertiesKey, + mutQuarantineProps, NULL); ::CFRelease(fileURL); ::CFRelease(mutQuarantineProps); } // Can be called off of the main thread. -void CopyQuarantineReferrerUrl(const CFStringRef aFilePath, nsAString& aReferrer) { - CFURLRef fileURL = - ::CFURLCreateWithFileSystemPath(kCFAllocatorDefault, aFilePath, kCFURLPOSIXPathStyle, false); +void CopyQuarantineReferrerUrl(const CFStringRef aFilePath, + nsAString& aReferrer) { + CFURLRef fileURL = ::CFURLCreateWithFileSystemPath( + kCFAllocatorDefault, aFilePath, kCFURLPOSIXPathStyle, false); - CFMutableDictionaryRef mutQuarantineProps = CreateQuarantineDictionary(fileURL, false); + CFMutableDictionaryRef mutQuarantineProps = + CreateQuarantineDictionary(fileURL, false); ::CFRelease(fileURL); if (!mutQuarantineProps) { return; } - CFTypeRef referrerRef = ::CFDictionaryGetValue(mutQuarantineProps, kLSQuarantineOriginURLKey); + CFTypeRef referrerRef = + ::CFDictionaryGetValue(mutQuarantineProps, kLSQuarantineOriginURLKey); if (referrerRef && ::CFGetTypeID(referrerRef) == ::CFURLGetTypeID()) { // URL string must be copied prior to releasing the dictionary. mozilla::CopyCocoaStringToXPCOMString( - (NSString*)::CFURLGetString(static_cast(referrerRef)), aReferrer); + (NSString*)::CFURLGetString(static_cast(referrerRef)), + aReferrer); } ::CFRelease(mutQuarantineProps); @@ -275,14 +297,18 @@ void CopyQuarantineReferrerUrl(const CFStringRef aFilePath, nsAString& aReferrer CFURLRef GetTemporaryFolderCFURLRef() { NSString* tempDir = ::NSTemporaryDirectory(); - return tempDir == nil ? NULL : (CFURLRef)[NSURL fileURLWithPath:tempDir isDirectory:YES]; + return tempDir == nil + ? NULL + : (CFURLRef)[NSURL fileURLWithPath:tempDir isDirectory:YES]; } CFURLRef GetProductDirectoryCFURLRef(bool aLocal) { - NSSearchPathDirectory folderType = aLocal ? NSCachesDirectory : NSLibraryDirectory; + NSSearchPathDirectory folderType = + aLocal ? NSCachesDirectory : NSLibraryDirectory; NSFileManager* manager = [NSFileManager defaultManager]; - return static_cast([[manager URLsForDirectory:folderType - inDomains:NSUserDomainMask] firstObject]); + return static_cast( + [[manager URLsForDirectory:folderType + inDomains:NSUserDomainMask] firstObject]); } } // namespace CocoaFileUtils diff --git a/xpcom/tests/gtest/TestMacNSURLEscaping.mm b/xpcom/tests/gtest/TestMacNSURLEscaping.mm index 35f5bcb3e59a..bbb0c8e2e92f 100644 --- a/xpcom/tests/gtest/TestMacNSURLEscaping.mm +++ b/xpcom/tests/gtest/TestMacNSURLEscaping.mm @@ -22,7 +22,8 @@ void ExpectUnchangedByNSURL(nsCString& aEncoded) { nsString geckoURLString; nsCocoaUtils::GetStringForNSString(macURLString, geckoURLString); - EXPECT_STREQ(aEncoded.BeginReading(), NS_ConvertUTF16toUTF8(geckoURLString).get()); + EXPECT_STREQ(aEncoded.BeginReading(), + NS_ConvertUTF16toUTF8(geckoURLString).get()); } // Test escaping of URLs to ensure that diff --git a/xpcom/tests/gtest/TestThreads_mac.mm b/xpcom/tests/gtest/TestThreads_mac.mm index c221452684ef..cb6e1c83cc22 100644 --- a/xpcom/tests/gtest/TestThreads_mac.mm +++ b/xpcom/tests/gtest/TestThreads_mac.mm @@ -20,18 +20,20 @@ bool UiThreadRunsRunLoop(bool aIsUiThread) { nsCOMPtr thread; nsIThreadManager::ThreadCreationOptions options; options.isUiThread = aIsUiThread; - MOZ_ALWAYS_SUCCEEDS( - NS_NewNamedThread("Testing Thread", getter_AddRefs(thread), nullptr, options)); + MOZ_ALWAYS_SUCCEEDS(NS_NewNamedThread( + "Testing Thread", getter_AddRefs(thread), nullptr, options)); __block bool blockRanInRunLoop = false; { - // We scope this so `loop` doesn't live past `thread-Shutdown()` since this file is compiled - // without ARC. + // We scope this so `loop` doesn't live past `thread-Shutdown()` since this + // file is compiled without ARC. NSRunLoop* loop = nil; - auto syncRunnable = MakeRefPtr(NS_NewRunnableFunction(__func__, [&] { - // If the thread doesn't already have an NSRunLoop, one will be created. - loop = NSRunLoop.currentRunLoop; - })); + auto syncRunnable = + MakeRefPtr(NS_NewRunnableFunction(__func__, [&] { + // If the thread doesn't already have an NSRunLoop, one will be + // created. + loop = NSRunLoop.currentRunLoop; + })); MOZ_ALWAYS_SUCCEEDS(syncRunnable->DispatchToThread(thread)); [loop performBlock:^void() {