clang-format objc files (#12673)

This commit is contained in:
Shelley Vohr 2018-04-20 14:47:04 -04:00 committed by Charles Kerr
parent 94236bf4eb
commit 12a57ff1c2
54 changed files with 1298 additions and 1033 deletions

View file

@ -14,11 +14,11 @@
if (inColorString) {
NSScanner* scanner = [NSScanner scannerWithString:inColorString];
(void) [scanner scanHexInt:&colorCode]; // ignore error
(void)[scanner scanHexInt:&colorCode]; // ignore error
}
redByte = (unsigned char)(colorCode >> 16);
greenByte = (unsigned char)(colorCode >> 8);
blueByte = (unsigned char)(colorCode); // masks off high bits
blueByte = (unsigned char)(colorCode); // masks off high bits
return [NSColor colorWithCalibratedRed:(CGFloat)redByte / 0xff
green:(CGFloat)greenByte / 0xff

View file

@ -4,8 +4,8 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/cocoa/NSString+ANSI.h"
#include "atom/browser/ui/cocoa/NSColor+Hex.h"
#include "atom/browser/ui/cocoa/NSString+ANSI.h"
#include "base/mac/scoped_nsobject.h"
@implementation NSMutableDictionary (ANSI)
@ -22,7 +22,8 @@
case 0:
[self removeAllObjects];
// remove italic and bold from font here
if (font) self[NSFontAttributeName] = font;
if (font)
self[NSFontAttributeName] = font;
break;
case 1:
@ -30,34 +31,42 @@
bold = (code == 1);
break;
// case 3: italic
// case 23: italic off
// case 4: underlined
// case 24: underlined off
// case 3: italic
// case 23: italic off
// case 4: underlined
// case 24: underlined off
case 30:
self[NSForegroundColorAttributeName] = [NSColor colorWithHexColorString:bold ? @"7f7f7f" : @"000000"];
self[NSForegroundColorAttributeName] =
[NSColor colorWithHexColorString:bold ? @"7f7f7f" : @"000000"];
break;
case 31:
self[NSForegroundColorAttributeName] = [NSColor colorWithHexColorString:bold ? @"cd0000" : @"ff0000"];
self[NSForegroundColorAttributeName] =
[NSColor colorWithHexColorString:bold ? @"cd0000" : @"ff0000"];
break;
case 32:
self[NSForegroundColorAttributeName] = [NSColor colorWithHexColorString:bold ? @"00cd00" : @"00ff00"];
self[NSForegroundColorAttributeName] =
[NSColor colorWithHexColorString:bold ? @"00cd00" : @"00ff00"];
break;
case 33:
self[NSForegroundColorAttributeName] = [NSColor colorWithHexColorString:bold ? @"cdcd00" : @"ffff00"];
self[NSForegroundColorAttributeName] =
[NSColor colorWithHexColorString:bold ? @"cdcd00" : @"ffff00"];
break;
case 34:
self[NSForegroundColorAttributeName] = [NSColor colorWithHexColorString:bold ? @"0000ee" : @"5c5cff"];
self[NSForegroundColorAttributeName] =
[NSColor colorWithHexColorString:bold ? @"0000ee" : @"5c5cff"];
break;
case 35:
self[NSForegroundColorAttributeName] = [NSColor colorWithHexColorString:bold ? @"cd00cd" : @"ff00ff"];
self[NSForegroundColorAttributeName] =
[NSColor colorWithHexColorString:bold ? @"cd00cd" : @"ff00ff"];
break;
case 36:
self[NSForegroundColorAttributeName] = [NSColor colorWithHexColorString:bold ? @"00cdcd" : @"00ffff"];
self[NSForegroundColorAttributeName] =
[NSColor colorWithHexColorString:bold ? @"00cdcd" : @"00ffff"];
break;
case 37:
self[NSForegroundColorAttributeName] = [NSColor colorWithHexColorString:bold ? @"e5e5e5" : @"ffffff"];
self[NSForegroundColorAttributeName] =
[NSColor colorWithHexColorString:bold ? @"e5e5e5" : @"ffffff"];
break;
case 39:
@ -65,28 +74,36 @@
break;
case 40:
self[NSBackgroundColorAttributeName] = [NSColor colorWithHexColorString:@"7f7f7f"];
self[NSBackgroundColorAttributeName] =
[NSColor colorWithHexColorString:@"7f7f7f"];
break;
case 41:
self[NSBackgroundColorAttributeName] = [NSColor colorWithHexColorString:@"cd0000"];
self[NSBackgroundColorAttributeName] =
[NSColor colorWithHexColorString:@"cd0000"];
break;
case 42:
self[NSBackgroundColorAttributeName] = [NSColor colorWithHexColorString:@"00cd00"];
self[NSBackgroundColorAttributeName] =
[NSColor colorWithHexColorString:@"00cd00"];
break;
case 43:
self[NSBackgroundColorAttributeName] = [NSColor colorWithHexColorString:@"cdcd00"];
self[NSBackgroundColorAttributeName] =
[NSColor colorWithHexColorString:@"cdcd00"];
break;
case 44:
self[NSBackgroundColorAttributeName] = [NSColor colorWithHexColorString:@"0000ee"];
self[NSBackgroundColorAttributeName] =
[NSColor colorWithHexColorString:@"0000ee"];
break;
case 45:
self[NSBackgroundColorAttributeName] = [NSColor colorWithHexColorString:@"cd00cd"];
self[NSBackgroundColorAttributeName] =
[NSColor colorWithHexColorString:@"cd00cd"];
break;
case 46:
self[NSBackgroundColorAttributeName] = [NSColor colorWithHexColorString:@"00cdcd"];
self[NSBackgroundColorAttributeName] =
[NSColor colorWithHexColorString:@"00cdcd"];
break;
case 47:
self[NSBackgroundColorAttributeName] = [NSColor colorWithHexColorString:@"e5e5e5"];
self[NSBackgroundColorAttributeName] =
[NSColor colorWithHexColorString:@"e5e5e5"];
break;
case 49:
@ -119,7 +136,8 @@
initWithString:parts.firstObject
attributes:nil] autorelease]];
for (NSString* part in [parts subarrayWithRange:NSMakeRange(1, parts.count - 1)]) {
for (NSString* part in
[parts subarrayWithRange:NSMakeRange(1, parts.count - 1)]) {
if (part.length == 0)
continue;
@ -127,16 +145,18 @@
NSString* text = sequence.lastObject;
if (sequence.count < 2) {
[result appendAttributedString:[[[NSAttributedString alloc]
initWithString:text
attributes:attributes] autorelease]];
[result
appendAttributedString:[[[NSAttributedString alloc]
initWithString:text
attributes:attributes] autorelease]];
} else if (sequence.count >= 2) {
text = [[sequence subarrayWithRange:NSMakeRange(1, sequence.count - 1)]
componentsJoinedByString:@"m"];
componentsJoinedByString:@"m"];
[attributes modifyAttributesForANSICodes:sequence[0]];
[result appendAttributedString:[[[NSAttributedString alloc]
initWithString:text
attributes:attributes] autorelease]];
[result
appendAttributedString:[[[NSAttributedString alloc]
initWithString:text
attributes:attributes] autorelease]];
}
}

View file

@ -8,8 +8,8 @@
#import <Foundation/Foundation.h>
#import <Security/Security.h>
#import <dlfcn.h>
#import <sys/param.h>
#import <sys/mount.h>
#import <sys/param.h>
#import "atom/browser/browser.h"
@ -24,22 +24,29 @@ bool AtomBundleMover::Move(mate::Arguments* args) {
NSString* bundlePath = [[NSBundle mainBundle] bundlePath];
// Skip if the application is already in the Applications folder
if (IsInApplicationsFolder(bundlePath)) return true;
if (IsInApplicationsFolder(bundlePath))
return true;
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString* diskImageDevice = ContainingDiskImageDevice(bundlePath);
NSString *applicationsDirectory = [[NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSLocalDomainMask, true) lastObject] stringByResolvingSymlinksInPath];
NSString *bundleName = [bundlePath lastPathComponent];
NSString *destinationPath = [applicationsDirectory stringByAppendingPathComponent:bundleName];
NSString* applicationsDirectory = [[NSSearchPathForDirectoriesInDomains(
NSApplicationDirectory, NSLocalDomainMask, true) lastObject]
stringByResolvingSymlinksInPath];
NSString* bundleName = [bundlePath lastPathComponent];
NSString* destinationPath =
[applicationsDirectory stringByAppendingPathComponent:bundleName];
// Check if we can write to the applications directory
// and then make sure that if the app already exists we can overwrite it
bool needAuthorization = ![fileManager isWritableFileAtPath:applicationsDirectory]
| ([fileManager fileExistsAtPath:destinationPath] && ![fileManager isWritableFileAtPath:destinationPath]);
bool needAuthorization =
![fileManager isWritableFileAtPath:applicationsDirectory] |
([fileManager fileExistsAtPath:destinationPath] &&
![fileManager isWritableFileAtPath:destinationPath]);
// Activate app -- work-around for focus issues related to "scary file from internet" OS dialog.
// Activate app -- work-around for focus issues related to "scary file from
// internet" OS dialog.
if (![NSApp isActive]) {
[NSApp activateIgnoringOtherApps:true];
}
@ -48,14 +55,15 @@ bool AtomBundleMover::Move(mate::Arguments* args) {
if (needAuthorization) {
bool authorizationCanceled;
if (!AuthorizedInstall(bundlePath, destinationPath, &authorizationCanceled)) {
if (!AuthorizedInstall(bundlePath, destinationPath,
&authorizationCanceled)) {
if (authorizationCanceled) {
// User rejected the authorization request
args->ThrowError("User rejected the authorization request");
return false;
}
else {
args->ThrowError("Failed to copy to applications directory even with authorization");
} else {
args->ThrowError(
"Failed to copy to applications directory even with authorization");
return false;
}
}
@ -65,11 +73,16 @@ bool AtomBundleMover::Move(mate::Arguments* args) {
// But first, make sure that it's not running
if (IsApplicationAtPathRunning(destinationPath)) {
// Give the running app focus and terminate myself
[[NSTask launchedTaskWithLaunchPath:@"/usr/bin/open" arguments:[NSArray arrayWithObject:destinationPath]] waitUntilExit];
[[NSTask
launchedTaskWithLaunchPath:@"/usr/bin/open"
arguments:[NSArray
arrayWithObject:destinationPath]]
waitUntilExit];
atom::Browser::Get()->Quit();
return true;
} else {
if (!Trash([applicationsDirectory stringByAppendingPathComponent:bundleName])) {
if (!Trash([applicationsDirectory
stringByAppendingPathComponent:bundleName])) {
args->ThrowError("Failed to delete existing application");
return false;
}
@ -77,15 +90,17 @@ bool AtomBundleMover::Move(mate::Arguments* args) {
}
if (!CopyBundle(bundlePath, destinationPath)) {
args->ThrowError("Failed to copy current bundle to the applications folder");
args->ThrowError(
"Failed to copy current bundle to the applications folder");
return false;
}
}
// Trash the original app. It's okay if this fails.
// NOTE: This final delete does not work if the source bundle is in a network mounted volume.
// Calling rm or file manager's delete method doesn't work either. It's unlikely to happen
// but it'd be great if someone could fix this.
// NOTE: This final delete does not work if the source bundle is in a network
// mounted volume.
// Calling rm or file manager's delete method doesn't work either. It's
// unlikely to happen but it'd be great if someone could fix this.
if (diskImageDevice == nil && !DeleteOrTrash(bundlePath)) {
// Could not delete original but we just don't care
}
@ -93,11 +108,15 @@ bool AtomBundleMover::Move(mate::Arguments* args) {
// Relaunch.
Relaunch(destinationPath);
// Launched from within a disk image? -- unmount (if no files are open after 5 seconds,
// otherwise leave it mounted).
// Launched from within a disk image? -- unmount (if no files are open after 5
// seconds, otherwise leave it mounted).
if (diskImageDevice) {
NSString *script = [NSString stringWithFormat:@"(/bin/sleep 5 && /usr/bin/hdiutil detach %@) &", ShellQuotedString(diskImageDevice)];
[NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:[NSArray arrayWithObjects:@"-c", script, nil]];
NSString* script = [NSString
stringWithFormat:@"(/bin/sleep 5 && /usr/bin/hdiutil detach %@) &",
ShellQuotedString(diskImageDevice)];
[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
arguments:[NSArray arrayWithObjects:@"-c", script,
nil]];
}
atom::Browser::Get()->Quit();
@ -106,18 +125,22 @@ bool AtomBundleMover::Move(mate::Arguments* args) {
}
bool AtomBundleMover::IsCurrentAppInApplicationsFolder() {
return IsInApplicationsFolder([[NSBundle mainBundle] bundlePath]);
return IsInApplicationsFolder([[NSBundle mainBundle] bundlePath]);
}
bool AtomBundleMover::IsInApplicationsFolder(NSString* bundlePath) {
// Check all the normal Application directories
NSArray* applicationDirs = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSAllDomainsMask, true);
NSArray* applicationDirs = NSSearchPathForDirectoriesInDomains(
NSApplicationDirectory, NSAllDomainsMask, true);
for (NSString* appDir in applicationDirs) {
if ([bundlePath hasPrefix:appDir]) return true;
if ([bundlePath hasPrefix:appDir])
return true;
}
// Also, handle the case that the user has some other Application directory (perhaps on a separate data partition).
if ([[bundlePath pathComponents] containsObject:@"Applications"]) return true;
// Also, handle the case that the user has some other Application directory
// (perhaps on a separate data partition).
if ([[bundlePath pathComponents] containsObject:@"Applications"])
return true;
return false;
}
@ -126,43 +149,61 @@ NSString* AtomBundleMover::ContainingDiskImageDevice(NSString* bundlePath) {
NSString* containingPath = [bundlePath stringByDeletingLastPathComponent];
struct statfs fs;
if (statfs([containingPath fileSystemRepresentation], &fs) || (fs.f_flags & MNT_ROOTFS))
if (statfs([containingPath fileSystemRepresentation], &fs) ||
(fs.f_flags & MNT_ROOTFS))
return nil;
NSString *device = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:fs.f_mntfromname length:strlen(fs.f_mntfromname)];
NSString* device = [[NSFileManager defaultManager]
stringWithFileSystemRepresentation:fs.f_mntfromname
length:strlen(fs.f_mntfromname)];
NSTask *hdiutil = [[[NSTask alloc] init] autorelease];
NSTask* hdiutil = [[[NSTask alloc] init] autorelease];
[hdiutil setLaunchPath:@"/usr/bin/hdiutil"];
[hdiutil setArguments:[NSArray arrayWithObjects:@"info", @"-plist", nil]];
[hdiutil setStandardOutput:[NSPipe pipe]];
[hdiutil launch];
[hdiutil waitUntilExit];
NSData *data = [[[hdiutil standardOutput] fileHandleForReading] readDataToEndOfFile];
NSData* data =
[[[hdiutil standardOutput] fileHandleForReading] readDataToEndOfFile];
NSDictionary *info = nil;
NSDictionary* info = nil;
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5) {
info = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:NULL error:NULL];
info = [NSPropertyListSerialization
propertyListWithData:data
options:NSPropertyListImmutable
format:NULL
error:NULL];
} else {
info = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:NULL];
info = [NSPropertyListSerialization
propertyListFromData:data
mutabilityOption:NSPropertyListImmutable
format:NULL
errorDescription:NULL];
}
if (![info isKindOfClass:[NSDictionary class]]) return nil;
if (![info isKindOfClass:[NSDictionary class]])
return nil;
NSArray *images = (NSArray *)[info objectForKey:@"images"];
if (![images isKindOfClass:[NSArray class]]) return nil;
NSArray* images = (NSArray*)[info objectForKey:@"images"];
if (![images isKindOfClass:[NSArray class]])
return nil;
for (NSDictionary *image in images) {
if (![image isKindOfClass:[NSDictionary class]]) return nil;
for (NSDictionary* image in images) {
if (![image isKindOfClass:[NSDictionary class]])
return nil;
id systemEntities = [image objectForKey:@"system-entities"];
if (![systemEntities isKindOfClass:[NSArray class]]) return nil;
if (![systemEntities isKindOfClass:[NSArray class]])
return nil;
for (NSDictionary *systemEntity in systemEntities) {
if (![systemEntity isKindOfClass:[NSDictionary class]]) return nil;
for (NSDictionary* systemEntity in systemEntities) {
if (![systemEntity isKindOfClass:[NSDictionary class]])
return nil;
NSString *devEntry = [systemEntity objectForKey:@"dev-entry"];
if (![devEntry isKindOfClass:[NSString class]]) return nil;
NSString* devEntry = [systemEntity objectForKey:@"dev-entry"];
if (![devEntry isKindOfClass:[NSString class]])
return nil;
if ([devEntry isEqualToString:device])
return device;
@ -172,72 +213,99 @@ NSString* AtomBundleMover::ContainingDiskImageDevice(NSString* bundlePath) {
return nil;
}
bool AtomBundleMover::AuthorizedInstall(NSString* srcPath, NSString* dstPath, bool* canceled) {
if (canceled) *canceled = false;
bool AtomBundleMover::AuthorizedInstall(NSString* srcPath,
NSString* dstPath,
bool* canceled) {
if (canceled)
*canceled = false;
// Make sure that the destination path is an app bundle. We're essentially running 'sudo rm -rf'
// so we really don't want to screw this up.
if (![[dstPath pathExtension] isEqualToString:@"app"]) return false;
// Make sure that the destination path is an app bundle. We're essentially
// running 'sudo rm -rf' so we really don't want to screw this up.
if (![[dstPath pathExtension] isEqualToString:@"app"])
return false;
// Do some more checks
if ([[dstPath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) return false;
if ([[srcPath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) return false;
if ([[dstPath stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceCharacterSet]]
length] == 0)
return false;
if ([[srcPath stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceCharacterSet]]
length] == 0)
return false;
int pid, status;
AuthorizationRef myAuthorizationRef;
// Get the authorization
OSStatus err = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &myAuthorizationRef);
if (err != errAuthorizationSuccess) return false;
OSStatus err =
AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults, &myAuthorizationRef);
if (err != errAuthorizationSuccess)
return false;
AuthorizationItem myItems = {kAuthorizationRightExecute, 0, NULL, 0};
AuthorizationRights myRights = {1, &myItems};
AuthorizationFlags myFlags = (AuthorizationFlags)(kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize);
AuthorizationFlags myFlags = (AuthorizationFlags)(
kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights |
kAuthorizationFlagPreAuthorize);
err = AuthorizationCopyRights(myAuthorizationRef, &myRights, NULL, myFlags, NULL);
err = AuthorizationCopyRights(myAuthorizationRef, &myRights, NULL, myFlags,
NULL);
if (err != errAuthorizationSuccess) {
if (err == errAuthorizationCanceled && canceled)
*canceled = true;
goto fail;
}
static OSStatus (*security_AuthorizationExecuteWithPrivileges)(AuthorizationRef authorization, const char *pathToTool,
AuthorizationFlags options, char * const *arguments,
FILE **communicationsPipe) = NULL;
static OSStatus (*security_AuthorizationExecuteWithPrivileges)(
AuthorizationRef authorization, const char* pathToTool,
AuthorizationFlags options, char* const* arguments,
FILE** communicationsPipe) = NULL;
if (!security_AuthorizationExecuteWithPrivileges) {
// On 10.7, AuthorizationExecuteWithPrivileges is deprecated. We want to still use it since there's no
// good alternative (without requiring code signing). We'll look up the function through dyld and fail
// if it is no longer accessible. If Apple removes the function entirely this will fail gracefully. If
// they keep the function and throw some sort of exception, this won't fail gracefully, but that's a
// risk we'll have to take for now.
security_AuthorizationExecuteWithPrivileges = (OSStatus (*)(AuthorizationRef, const char*,
AuthorizationFlags, char* const*,
FILE **)) dlsym(RTLD_DEFAULT, "AuthorizationExecuteWithPrivileges");
// On 10.7, AuthorizationExecuteWithPrivileges is deprecated. We want to
// still use it since there's no good alternative (without requiring code
// signing). We'll look up the function through dyld and fail if it is no
// longer accessible. If Apple removes the function entirely this will fail
// gracefully. If they keep the function and throw some sort of exception,
// this won't fail gracefully, but that's a risk we'll have to take for now.
security_AuthorizationExecuteWithPrivileges = (OSStatus(*)(
AuthorizationRef, const char*, AuthorizationFlags, char* const*,
FILE**))dlsym(RTLD_DEFAULT, "AuthorizationExecuteWithPrivileges");
}
if (!security_AuthorizationExecuteWithPrivileges) goto fail;
if (!security_AuthorizationExecuteWithPrivileges)
goto fail;
// Delete the destination
{
char rf[] = "-rf";
char *args[] = {rf, (char *)[dstPath fileSystemRepresentation], NULL};
err = security_AuthorizationExecuteWithPrivileges(myAuthorizationRef, "/bin/rm", kAuthorizationFlagDefaults, args, NULL);
if (err != errAuthorizationSuccess) goto fail;
char* args[] = {rf, (char*)[dstPath fileSystemRepresentation], NULL};
err = security_AuthorizationExecuteWithPrivileges(
myAuthorizationRef, "/bin/rm", kAuthorizationFlagDefaults, args, NULL);
if (err != errAuthorizationSuccess)
goto fail;
// Wait until it's done
pid = wait(&status);
if (pid == -1 || !WIFEXITED(status)) goto fail; // We don't care about exit status as the destination most likely does not exist
if (pid == -1 || !WIFEXITED(status))
goto fail; // We don't care about exit status as the destination most
// likely does not exist
}
// Copy
{
char pR[] = "-pR";
char *args[] = {pR, (char *)[srcPath fileSystemRepresentation], (char *)[dstPath fileSystemRepresentation], NULL};
err = security_AuthorizationExecuteWithPrivileges(myAuthorizationRef, "/bin/cp", kAuthorizationFlagDefaults, args, NULL);
if (err != errAuthorizationSuccess) goto fail;
char* args[] = {pR, (char*)[srcPath fileSystemRepresentation],
(char*)[dstPath fileSystemRepresentation], NULL};
err = security_AuthorizationExecuteWithPrivileges(
myAuthorizationRef, "/bin/cp", kAuthorizationFlagDefaults, args, NULL);
if (err != errAuthorizationSuccess)
goto fail;
// Wait until it's done
pid = wait(&status);
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status)) goto fail;
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status))
goto fail;
}
AuthorizationFree(myAuthorizationRef, kAuthorizationFlagDefaults);
@ -254,14 +322,16 @@ bool AtomBundleMover::CopyBundle(NSString* srcPath, NSString* dstPath) {
if ([fileManager copyItemAtPath:srcPath toPath:dstPath error:&error]) {
return true;
}
else {
} else {
return false;
}
}
NSString* AtomBundleMover::ShellQuotedString(NSString* string) {
return [NSString stringWithFormat:@"'%@'", [string stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
return [NSString
stringWithFormat:@"'%@'",
[string stringByReplacingOccurrencesOfString:@"'"
withString:@"'\\''"]];
}
void AtomBundleMover::Relaunch(NSString* destinationPath) {
@ -276,18 +346,28 @@ void AtomBundleMover::Relaunch(NSString* destinationPath) {
// Before we launch the new app, clear xattr:com.apple.quarantine to avoid
// duplicate "scary file from the internet" dialog.
preOpenCmd = [NSString stringWithFormat:@"/usr/bin/xattr -d -r com.apple.quarantine %@", quotedDestinationPath];
preOpenCmd = [NSString
stringWithFormat:@"/usr/bin/xattr -d -r com.apple.quarantine %@",
quotedDestinationPath];
NSString* script = [NSString stringWithFormat:@"(while /bin/kill -0 %d >&/dev/null; do /bin/sleep 0.1; done; %@; /usr/bin/open %@) &", pid, preOpenCmd, quotedDestinationPath];
NSString* script =
[NSString stringWithFormat:
@"(while /bin/kill -0 %d >&/dev/null; do /bin/sleep 0.1; "
@"done; %@; /usr/bin/open %@) &",
pid, preOpenCmd, quotedDestinationPath];
[NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:[NSArray arrayWithObjects:@"-c", script, nil]];
[NSTask
launchedTaskWithLaunchPath:@"/bin/sh"
arguments:[NSArray arrayWithObjects:@"-c", script, nil]];
}
bool AtomBundleMover::IsApplicationAtPathRunning(NSString* bundlePath) {
bundlePath = [bundlePath stringByStandardizingPath];
for (NSRunningApplication *runningApplication in [[NSWorkspace sharedWorkspace] runningApplications]) {
NSString* runningAppBundlePath = [[[runningApplication bundleURL] path] stringByStandardizingPath];
for (NSRunningApplication* runningApplication in
[[NSWorkspace sharedWorkspace] runningApplications]) {
NSString* runningAppBundlePath =
[[[runningApplication bundleURL] path] stringByStandardizingPath];
if ([runningAppBundlePath isEqualToString:bundlePath]) {
return true;
}
@ -299,29 +379,41 @@ bool AtomBundleMover::Trash(NSString* path) {
bool result = false;
if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_8) {
result = [[NSFileManager defaultManager] trashItemAtURL:[NSURL fileURLWithPath:path] resultingItemURL:NULL error:NULL];
result = [[NSFileManager defaultManager]
trashItemAtURL:[NSURL fileURLWithPath:path]
resultingItemURL:NULL
error:NULL];
}
if (!result) {
result = [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation
source:[path stringByDeletingLastPathComponent]
destination:@""
files:[NSArray arrayWithObject:[path lastPathComponent]]
tag:NULL];
result = [[NSWorkspace sharedWorkspace]
performFileOperation:NSWorkspaceRecycleOperation
source:[path stringByDeletingLastPathComponent]
destination:@""
files:[NSArray arrayWithObject:[path lastPathComponent]]
tag:NULL];
}
// As a last resort try trashing with AppleScript.
// This allows us to trash the app in macOS Sierra even when the app is running inside
// an app translocation image.
// This allows us to trash the app in macOS Sierra even when the app is
// running inside an app translocation image.
if (!result) {
NSAppleScript* appleScript = [[[NSAppleScript alloc] initWithSource:
[NSString stringWithFormat:@"\
set theFile to POSIX file \"%@\" \n\
tell application \"Finder\" \n\
NSAppleScript* appleScript = [[[NSAppleScript alloc]
initWithSource:
[NSString
stringWithFormat:
@"\
set theFile to POSIX file \"%@\" "
@"\n\
tell application \"Finder\" "
@"\n\
move theFile to trash \n\
end tell", path]] autorelease];
"
@" end tell",
path]] autorelease];
NSDictionary* errorDict = nil;
NSAppleEventDescriptor* scriptResult = [appleScript executeAndReturnError:&errorDict];
NSAppleEventDescriptor* scriptResult =
[appleScript executeAndReturnError:&errorDict];
result = (scriptResult != nil);
}

View file

@ -25,35 +25,35 @@ struct Role {
const char* role;
};
Role kRolesMap[] = {
{ @selector(orderFrontStandardAboutPanel:), "about" },
{ @selector(hide:), "hide" },
{ @selector(hideOtherApplications:), "hideothers" },
{ @selector(unhideAllApplications:), "unhide" },
{ @selector(arrangeInFront:), "front" },
{ @selector(undo:), "undo" },
{ @selector(redo:), "redo" },
{ @selector(cut:), "cut" },
{ @selector(copy:), "copy" },
{ @selector(paste:), "paste" },
{ @selector(delete:), "delete" },
{ @selector(pasteAndMatchStyle:), "pasteandmatchstyle" },
{ @selector(selectAll:), "selectall" },
{ @selector(startSpeaking:), "startspeaking" },
{ @selector(stopSpeaking:), "stopspeaking" },
{ @selector(performMiniaturize:), "minimize" },
{ @selector(performClose:), "close" },
{ @selector(performZoom:), "zoom" },
{ @selector(terminate:), "quit" },
// ↓ is intentionally not `toggleFullScreen`. The macOS full screen menu item behaves weird.
// If we use `toggleFullScreen`, then the menu item will use the default label, and not take
// the one provided.
{ @selector(toggleFullScreenMode:), "togglefullscreen" },
{ @selector(toggleTabBar:), "toggletabbar" },
{ @selector(selectNextTab:), "selectnexttab" },
{ @selector(selectPreviousTab:), "selectprevioustab" },
{ @selector(mergeAllWindows:), "mergeallwindows" },
{ @selector(moveTabToNewWindow:), "movetabtonewwindow" },
{ @selector(clearRecentDocuments:), "clearrecentdocuments" },
{@selector(orderFrontStandardAboutPanel:), "about"},
{@selector(hide:), "hide"},
{@selector(hideOtherApplications:), "hideothers"},
{@selector(unhideAllApplications:), "unhide"},
{@selector(arrangeInFront:), "front"},
{@selector(undo:), "undo"},
{@selector(redo:), "redo"},
{@selector(cut:), "cut"},
{@selector(copy:), "copy"},
{@selector(paste:), "paste"},
{@selector(delete:), "delete"},
{@selector(pasteAndMatchStyle:), "pasteandmatchstyle"},
{@selector(selectAll:), "selectall"},
{@selector(startSpeaking:), "startspeaking"},
{@selector(stopSpeaking:), "stopspeaking"},
{@selector(performMiniaturize:), "minimize"},
{@selector(performClose:), "close"},
{@selector(performZoom:), "zoom"},
{@selector(terminate:), "quit"},
// ↓ is intentionally not `toggleFullScreen`. The macOS full screen menu
// item behaves weird. If we use `toggleFullScreen`, then the menu item will
// use the default label, and not take the one provided.
{@selector(toggleFullScreenMode:), "togglefullscreen"},
{@selector(toggleTabBar:), "toggletabbar"},
{@selector(selectNextTab:), "selectnexttab"},
{@selector(selectPreviousTab:), "selectprevioustab"},
{@selector(mergeAllWindows:), "mergeallwindows"},
{@selector(moveTabToNewWindow:), "movetabtonewwindow"},
{@selector(clearRecentDocuments:), "clearrecentdocuments"},
};
} // namespace
@ -68,7 +68,8 @@ static base::scoped_nsobject<NSMenu> recentDocumentsMenuSwap_;
@synthesize model = model_;
- (id)initWithModel:(atom::AtomMenuModel*)model useDefaultAccelerator:(BOOL)use {
- (id)initWithModel:(atom::AtomMenuModel*)model
useDefaultAccelerator:(BOOL)use {
if ((self = [super init])) {
model_ = model;
isMenuOpen_ = NO;
@ -100,10 +101,9 @@ static base::scoped_nsobject<NSMenu> recentDocumentsMenuSwap_;
if (!recentDocumentsMenuItem_) {
// Locate & retain the recent documents menu item
recentDocumentsMenuItem_.reset([[[[[NSApp mainMenu]
itemWithTitle:@"Electron"] submenu]
itemWithTitle:@"Open Recent"]
retain]);
recentDocumentsMenuItem_.reset(
[[[[[NSApp mainMenu] itemWithTitle:@"Electron"] submenu]
itemWithTitle:@"Open Recent"] retain]);
}
model_ = model;
@ -146,15 +146,13 @@ static base::scoped_nsobject<NSMenu> recentDocumentsMenuSwap_;
// Adds a separator item at the given index. As the separator doesn't need
// anything from the model, this method doesn't need the model index as the
// other method below does.
- (void)addSeparatorToMenu:(NSMenu*)menu
atIndex:(int)index {
- (void)addSeparatorToMenu:(NSMenu*)menu atIndex:(int)index {
NSMenuItem* separator = [NSMenuItem separatorItem];
[menu insertItem:separator atIndex:index];
}
// Empties the source menu items to the destination.
- (void)moveMenuItems:(NSMenu*)source
to:(NSMenu*)destination {
- (void)moveMenuItems:(NSMenu*)source to:(NSMenu*)destination {
const long count = [source numberOfItems];
for (long index = 0; index < count; index++) {
NSMenuItem* removedItem = [[[source itemAtIndex:0] retain] autorelease];
@ -166,12 +164,11 @@ static base::scoped_nsobject<NSMenu> recentDocumentsMenuSwap_;
// Replaces the item's submenu instance with the singleton recent documents
// menu. Previously replaced menu items will be recovered.
- (void)replaceSubmenuShowingRecentDocuments:(NSMenuItem*)item {
NSMenu* recentDocumentsMenu = [[[recentDocumentsMenuItem_ submenu]
retain] autorelease];
NSMenu* recentDocumentsMenu =
[[[recentDocumentsMenuItem_ submenu] retain] autorelease];
// Remove menu items in recent documents back to swap menu
[self moveMenuItems:recentDocumentsMenu
to:recentDocumentsMenuSwap_];
[self moveMenuItems:recentDocumentsMenu to:recentDocumentsMenuSwap_];
// Swap back the submenu
[recentDocumentsMenuItem_ setSubmenu:recentDocumentsMenuSwap_];
@ -179,8 +176,7 @@ static base::scoped_nsobject<NSMenu> recentDocumentsMenuSwap_;
recentDocumentsMenuSwap_.reset([[item submenu] retain]);
// Repopulate with items from the submenu to be replaced
[self moveMenuItems:recentDocumentsMenuSwap_
to:recentDocumentsMenu];
[self moveMenuItems:recentDocumentsMenuSwap_ to:recentDocumentsMenu];
// Update the submenu's title
[recentDocumentsMenu setTitle:[recentDocumentsMenuSwap_ title]];
// Replace submenu
@ -198,10 +194,10 @@ static base::scoped_nsobject<NSMenu> recentDocumentsMenuSwap_;
base::string16 label16 = model->GetLabelAt(index);
NSString* label = l10n_util::FixUpWindowsStyleLabel(label16);
base::scoped_nsobject<NSMenuItem> item(
[[NSMenuItem alloc] initWithTitle:label
action:@selector(itemSelected:)
keyEquivalent:@""]);
base::scoped_nsobject<NSMenuItem> item([[NSMenuItem alloc]
initWithTitle:label
action:@selector(itemSelected:)
keyEquivalent:@""]);
// If the menu item has an icon, set it.
gfx::Image icon;
@ -214,8 +210,8 @@ static base::scoped_nsobject<NSMenu> recentDocumentsMenuSwap_;
// Recursively build a submenu from the sub-model at this index.
[item setTarget:nil];
[item setAction:nil];
atom::AtomMenuModel* submenuModel = static_cast<atom::AtomMenuModel*>(
model->GetSubmenuModelAt(index));
atom::AtomMenuModel* submenuModel =
static_cast<atom::AtomMenuModel*>(model->GetSubmenuModelAt(index));
NSMenu* submenu = [self menuFromModel:submenuModel];
[submenu setTitle:[item title]];
[item setSubmenu:submenu];
@ -239,15 +235,15 @@ static base::scoped_nsobject<NSMenu> recentDocumentsMenuSwap_;
NSValue* modelObject = [NSValue valueWithPointer:model];
[item setRepresentedObject:modelObject]; // Retains |modelObject|.
ui::Accelerator accelerator;
if (model->GetAcceleratorAtWithParams(
index, useDefaultAccelerator_, &accelerator)) {
if (model->GetAcceleratorAtWithParams(index, useDefaultAccelerator_,
&accelerator)) {
const ui::PlatformAcceleratorCocoa* platformAccelerator =
static_cast<const ui::PlatformAcceleratorCocoa*>(
accelerator.platform_accelerator());
if (platformAccelerator) {
[item setKeyEquivalent:platformAccelerator->characters()];
[item setKeyEquivalentModifierMask:
platformAccelerator->modifier_mask()];
[item
setKeyEquivalentModifierMask:platformAccelerator->modifier_mask()];
}
}
@ -275,9 +271,8 @@ static base::scoped_nsobject<NSMenu> recentDocumentsMenuSwap_;
return NO;
NSInteger modelIndex = [item tag];
atom::AtomMenuModel* model =
static_cast<atom::AtomMenuModel*>(
[[(id)item representedObject] pointerValue]);
atom::AtomMenuModel* model = static_cast<atom::AtomMenuModel*>(
[[(id)item representedObject] pointerValue]);
DCHECK(model);
if (model) {
BOOL checked = model->IsItemCheckedAt(modelIndex);
@ -303,9 +298,8 @@ static base::scoped_nsobject<NSMenu> recentDocumentsMenuSwap_;
// item chosen.
- (void)itemSelected:(id)sender {
NSInteger modelIndex = [sender tag];
atom::AtomMenuModel* model =
static_cast<atom::AtomMenuModel*>(
[[sender representedObject] pointerValue]);
atom::AtomMenuModel* model = static_cast<atom::AtomMenuModel*>(
[[sender representedObject] pointerValue]);
DCHECK(model);
if (model) {
NSEvent* event = [NSApp currentEvent];
@ -338,8 +332,8 @@ static base::scoped_nsobject<NSMenu> recentDocumentsMenuSwap_;
if (isMenuOpen_) {
isMenuOpen_ = NO;
model_->MenuWillClose();
// Post async task so that itemSelected runs before the close callback
// deletes the controller from the map which deallocates it
// Post async task so that itemSelected runs before the close callback
// deletes the controller from the map which deallocates it
if (!closeCallback.is_null()) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, closeCallback);
}

View file

@ -8,11 +8,9 @@ namespace atom {
AtomNativeWidgetMac::AtomNativeWidgetMac(
views::internal::NativeWidgetDelegate* delegate)
: views::NativeWidgetMac(delegate) {
}
: views::NativeWidgetMac(delegate) {}
AtomNativeWidgetMac::~AtomNativeWidgetMac() {
}
AtomNativeWidgetMac::~AtomNativeWidgetMac() {}
NativeWidgetMacNSWindow* AtomNativeWidgetMac::CreateNSWindow(
const views::Widget::InitParams& params) {

View file

@ -36,7 +36,7 @@ bool ScopedDisableResize::disable_resize_ = false;
// NSWindow overrides.
- (void)swipeWithEvent:(NSEvent *)event {
- (void)swipeWithEvent:(NSEvent*)event {
if (event.deltaY == 1.0) {
shell_->NotifyWindowSwipe("up");
} else if (event.deltaX == -1.0) {
@ -78,12 +78,11 @@ bool ScopedDisableResize::disable_resize_ = false;
// * when VoiceOver is enabled, the full accessibility tree is used.
// Without removing the title and with VO disabled, the TTS would always read
// the window title instead of using Cmd+C to get the selected text.
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"(self isKindOfClass: %@) OR (self.className == %@)",
[NSButtonCell class],
@"RenderWidgetHostViewCocoa"];
NSPredicate* predicate = [NSPredicate
predicateWithFormat:@"(self isKindOfClass: %@) OR (self.className == %@)",
[NSButtonCell class], @"RenderWidgetHostViewCocoa"];
NSArray *children = [super accessibilityAttributeValue:attribute];
NSArray* children = [super accessibilityAttributeValue:attribute];
return [children filteredArrayUsingPredicate:predicate];
}
@ -97,7 +96,8 @@ bool ScopedDisableResize::disable_resize_ = false;
- (void)enableWindowButtonsOffset {
auto closeButton = [self standardWindowButton:NSWindowCloseButton];
auto miniaturizeButton = [self standardWindowButton:NSWindowMiniaturizeButton];
auto miniaturizeButton =
[self standardWindowButton:NSWindowMiniaturizeButton];
auto zoomButton = [self standardWindowButton:NSWindowZoomButton];
[closeButton setPostsFrameChangedNotifications:YES];
@ -105,7 +105,7 @@ bool ScopedDisableResize::disable_resize_ = false;
[zoomButton setPostsFrameChangedNotifications:YES];
windowButtonsInterButtonSpacing_ =
NSMinX([miniaturizeButton frame]) - NSMaxX([closeButton frame]);
NSMinX([miniaturizeButton frame]) - NSMaxX([closeButton frame]);
auto center = [NSNotificationCenter defaultCenter];
@ -126,39 +126,34 @@ bool ScopedDisableResize::disable_resize_ = false;
}
- (void)adjustCloseButton:(NSNotification*)notification {
[self adjustButton:[notification object]
ofKind:NSWindowCloseButton];
[self adjustButton:[notification object] ofKind:NSWindowCloseButton];
}
- (void)adjustMiniaturizeButton:(NSNotification*)notification {
[self adjustButton:[notification object]
ofKind:NSWindowMiniaturizeButton];
[self adjustButton:[notification object] ofKind:NSWindowMiniaturizeButton];
}
- (void)adjustZoomButton:(NSNotification*)notification {
[self adjustButton:[notification object]
ofKind:NSWindowZoomButton];
[self adjustButton:[notification object] ofKind:NSWindowZoomButton];
}
- (void)adjustButton:(NSButton*)button
ofKind:(NSWindowButton)kind {
- (void)adjustButton:(NSButton*)button ofKind:(NSWindowButton)kind {
NSRect buttonFrame = [button frame];
NSRect frameViewBounds = [[self frameView] bounds];
NSPoint offset = self.windowButtonsOffset;
buttonFrame.origin = NSMakePoint(
offset.x,
(NSHeight(frameViewBounds) - NSHeight(buttonFrame) - offset.y));
offset.x, (NSHeight(frameViewBounds) - NSHeight(buttonFrame) - offset.y));
switch (kind) {
case NSWindowZoomButton:
buttonFrame.origin.x += NSWidth(
[[self standardWindowButton:NSWindowMiniaturizeButton] frame]);
[[self standardWindowButton:NSWindowMiniaturizeButton] frame]);
buttonFrame.origin.x += windowButtonsInterButtonSpacing_;
// fallthrough
case NSWindowMiniaturizeButton:
buttonFrame.origin.x += NSWidth(
[[self standardWindowButton:NSWindowCloseButton] frame]);
buttonFrame.origin.x +=
NSWidth([[self standardWindowButton:NSWindowCloseButton] frame]);
buttonFrame.origin.x += windowButtonsInterButtonSpacing_;
// fallthrough
default:
@ -194,7 +189,8 @@ bool ScopedDisableResize::disable_resize_ = false;
// Custom window button methods
- (void)performClose:(id)sender {
if (shell_->title_bar_style() == atom::NativeWindowMac::CUSTOM_BUTTONS_ON_HOVER)
if (shell_->title_bar_style() ==
atom::NativeWindowMac::CUSTOM_BUTTONS_ON_HOVER)
[[self delegate] windowShouldClose:self];
else
[super performClose:sender];
@ -204,11 +200,12 @@ bool ScopedDisableResize::disable_resize_ = false;
if (shell_->simple_fullscreen())
shell_->SetSimpleFullScreen(!shell_->IsSimpleFullScreen());
else
[super toggleFullScreen:sender];
[super toggleFullScreen:sender];
}
- (void)performMiniaturize:(id)sender {
if (shell_->title_bar_style() == atom::NativeWindowMac::CUSTOM_BUTTONS_ON_HOVER)
if (shell_->title_bar_style() ==
atom::NativeWindowMac::CUSTOM_BUTTONS_ON_HOVER)
[self miniaturize:self];
else
[super performMiniaturize:sender];

View file

@ -23,19 +23,20 @@
#pragma mark - NSWindowDelegate
- (void)windowDidChangeOcclusionState:(NSNotification *)notification {
- (void)windowDidChangeOcclusionState:(NSNotification*)notification {
// notification.object is the window that changed its state.
// It's safe to use self.window instead if you don't assign one delegate to many windows
NSWindow *window = notification.object;
// It's safe to use self.window instead if you don't assign one delegate to
// many windows
NSWindow* window = notification.object;
// check occlusion binary flag
if (window.occlusionState & NSWindowOcclusionStateVisible) {
// The app is visible
shell_->NotifyWindowShow();
} else {
// The app is not visible
shell_->NotifyWindowHide();
}
if (window.occlusionState & NSWindowOcclusionStateVisible) {
// The app is visible
shell_->NotifyWindowShow();
} else {
// The app is not visible
shell_->NotifyWindowHide();
}
}
// Called when the user clicks the zoom button or selects it from the Window
@ -55,8 +56,8 @@
// Never shrink from the current size on zoom.
NSRect window_frame = [window frame];
CGFloat zoomed_width = std::max(static_cast<CGFloat>(preferred_width),
NSWidth(window_frame));
CGFloat zoomed_width =
std::max(static_cast<CGFloat>(preferred_width), NSWidth(window_frame));
// |frame| determines our maximum extents. We need to set the origin of the
// frame -- and only move it left if necessary.
@ -117,7 +118,8 @@
- (void)windowWillMiniaturize:(NSNotification*)notification {
NSWindow* window = shell_->GetNativeWindow();
// store the current status window level to be restored in windowDidDeminiaturize
// store the current status window level to be restored in
// windowDidDeminiaturize
level_ = [window level];
[window setLevel:NSNormalWindowLevel];
}
@ -177,16 +179,16 @@
[window setTitleVisibility:NSWindowTitleVisible];
}
// Restore the native toolbar immediately after entering fullscreen, if we do
// this before leaving fullscreen, traffic light buttons will be jumping.
// Restore the native toolbar immediately after entering fullscreen, if we
// do this before leaving fullscreen, traffic light buttons will be jumping.
if (shell_->title_bar_style() == atom::NativeWindowMac::HIDDEN_INSET) {
base::scoped_nsobject<NSToolbar> toolbar(
[[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"]);
[toolbar setShowsBaselineSeparator:NO];
[window setToolbar:toolbar];
// Set window style to hide the toolbar, otherwise the toolbar will show in
// fullscreen mode.
// Set window style to hide the toolbar, otherwise the toolbar will show
// in fullscreen mode.
shell_->SetStyleMask(true, NSFullSizeContentViewWindowMask);
}
}
@ -229,7 +231,8 @@
}
- (NSRect)window:(NSWindow*)window
willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect {
willPositionSheet:(NSWindow*)sheet
usingRect:(NSRect)rect {
NSView* view = window.contentView;
rect.origin.x = shell_->GetSheetOffsetX();
@ -237,11 +240,11 @@
return rect;
}
- (void)windowWillBeginSheet:(NSNotification *)notification {
- (void)windowWillBeginSheet:(NSNotification*)notification {
shell_->NotifyWindowSheetBegin();
}
- (void)windowDidEndSheet:(NSNotification *)notification {
- (void)windowDidEndSheet:(NSNotification*)notification {
shell_->NotifyWindowSheetEnd();
}
@ -253,7 +256,8 @@
#pragma mark - NSTouchBarDelegate
- (NSTouchBarItem*)touchBar:(NSTouchBar*)touchBar
makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier API_AVAILABLE(macosx(10.12.2)) {
makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier
API_AVAILABLE(macosx(10.12.2)) {
if (touchBar && shell_->touch_bar())
return [shell_->touch_bar() makeItemForIdentifier:identifier];
else
@ -266,8 +270,8 @@
return 1;
}
- (id <QLPreviewItem>)previewPanel:(QLPreviewPanel*)panel
previewItemAtIndex:(NSInteger)index {
- (id<QLPreviewItem>)previewPanel:(QLPreviewPanel*)panel
previewItemAtIndex:(NSInteger)index {
return shell_->preview_item();
}

View file

@ -12,21 +12,30 @@
@implementation AtomTouchBar
static NSTouchBarItemIdentifier ButtonIdentifier = @"com.electron.touchbar.button.";
static NSTouchBarItemIdentifier ColorPickerIdentifier = @"com.electron.touchbar.colorpicker.";
static NSTouchBarItemIdentifier GroupIdentifier = @"com.electron.touchbar.group.";
static NSTouchBarItemIdentifier LabelIdentifier = @"com.electron.touchbar.label.";
static NSTouchBarItemIdentifier PopoverIdentifier = @"com.electron.touchbar.popover.";
static NSTouchBarItemIdentifier SliderIdentifier = @"com.electron.touchbar.slider.";
static NSTouchBarItemIdentifier SegmentedControlIdentifier = @"com.electron.touchbar.segmentedcontrol.";
static NSTouchBarItemIdentifier ScrubberIdentifier = @"com.electron.touchbar.scrubber.";
static NSTouchBarItemIdentifier ButtonIdentifier =
@"com.electron.touchbar.button.";
static NSTouchBarItemIdentifier ColorPickerIdentifier =
@"com.electron.touchbar.colorpicker.";
static NSTouchBarItemIdentifier GroupIdentifier =
@"com.electron.touchbar.group.";
static NSTouchBarItemIdentifier LabelIdentifier =
@"com.electron.touchbar.label.";
static NSTouchBarItemIdentifier PopoverIdentifier =
@"com.electron.touchbar.popover.";
static NSTouchBarItemIdentifier SliderIdentifier =
@"com.electron.touchbar.slider.";
static NSTouchBarItemIdentifier SegmentedControlIdentifier =
@"com.electron.touchbar.segmentedcontrol.";
static NSTouchBarItemIdentifier ScrubberIdentifier =
@"com.electron.touchbar.scrubber.";
static NSString* const TextScrubberItemIdentifier = @"scrubber.text.item";
static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
- (id)initWithDelegate:(id<NSTouchBarDelegate>)delegate
window:(atom::NativeWindow*)window
settings:(const std::vector<mate::PersistentDictionary>&)settings {
settings:
(const std::vector<mate::PersistentDictionary>&)settings {
if ((self = [super init])) {
delegate_ = delegate;
window_ = window;
@ -36,7 +45,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
}
- (NSTouchBar*)makeTouchBar {
NSMutableArray* identifiers = [self identifiersFromSettings:ordered_settings_];
NSMutableArray* identifiers =
[self identifiersFromSettings:ordered_settings_];
return [self touchBarFromItemIdentifiers:identifiers];
}
@ -48,7 +58,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
return bar.autorelease();
}
- (NSMutableArray*)identifiersFromSettings:(const std::vector<mate::PersistentDictionary>&)dicts {
- (NSMutableArray*)identifiersFromSettings:
(const std::vector<mate::PersistentDictionary>&)dicts {
NSMutableArray* identifiers = [NSMutableArray array];
if (@available(macOS 10.12.2, *)) {
@ -93,7 +104,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
item_id = [self idFromIdentifier:identifier withPrefix:LabelIdentifier];
return [self makeLabelForID:item_id withIdentifier:identifier];
} else if ([identifier hasPrefix:ColorPickerIdentifier]) {
item_id = [self idFromIdentifier:identifier withPrefix:ColorPickerIdentifier];
item_id =
[self idFromIdentifier:identifier withPrefix:ColorPickerIdentifier];
return [self makeColorPickerForID:item_id withIdentifier:identifier];
} else if ([identifier hasPrefix:SliderIdentifier]) {
item_id = [self idFromIdentifier:identifier withPrefix:SliderIdentifier];
@ -105,7 +117,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
item_id = [self idFromIdentifier:identifier withPrefix:GroupIdentifier];
return [self makeGroupForID:item_id withIdentifier:identifier];
} else if ([identifier hasPrefix:SegmentedControlIdentifier]) {
item_id = [self idFromIdentifier:identifier withPrefix:SegmentedControlIdentifier];
item_id = [self idFromIdentifier:identifier
withPrefix:SegmentedControlIdentifier];
return [self makeSegmentedControlForID:item_id withIdentifier:identifier];
} else if ([identifier hasPrefix:ScrubberIdentifier]) {
item_id = [self idFromIdentifier:identifier withPrefix:ScrubberIdentifier];
@ -119,9 +132,10 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
id:(NSTouchBarItemIdentifier)identifier
withType:(const std::string&)item_type
withSettings:(const mate::PersistentDictionary&)settings
API_AVAILABLE(macosx(10.12.2)) {
API_AVAILABLE(macosx(10.12.2)) {
NSTouchBarItem* item = [touchBar itemForIdentifier:identifier];
if (!item) return;
if (!item)
return;
if (item_type == "button") {
[self updateButton:(NSCustomTouchBarItem*)item withSettings:settings];
@ -135,7 +149,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
} else if (item_type == "popover") {
[self updatePopover:(NSPopoverTouchBarItem*)item withSettings:settings];
} else if (item_type == "segmented_control") {
[self updateSegmentedControl:(NSCustomTouchBarItem*)item withSettings:settings];
[self updateSegmentedControl:(NSCustomTouchBarItem*)item
withSettings:settings];
} else if (item_type == "scrubber") {
[self updateScrubber:(NSCustomTouchBarItem*)item withSettings:settings];
} else if (item_type == "group") {
@ -143,12 +158,16 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
}
}
- (void)addNonDefaultTouchBarItems:(const std::vector<mate::PersistentDictionary>&)items {
- (void)addNonDefaultTouchBarItems:
(const std::vector<mate::PersistentDictionary>&)items {
[self identifiersFromSettings:items];
}
- (void)setEscapeTouchBarItem:(const mate::PersistentDictionary&)item forTouchBar:(NSTouchBar*)touchBar {
if (![touchBar respondsToSelector:@selector(escapeKeyReplacementItemIdentifier)]) return;
- (void)setEscapeTouchBarItem:(const mate::PersistentDictionary&)item
forTouchBar:(NSTouchBar*)touchBar {
if (![touchBar
respondsToSelector:@selector(escapeKeyReplacementItemIdentifier)])
return;
std::string type;
std::string item_id;
NSTouchBarItemIdentifier identifier = nil;
@ -156,7 +175,7 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
identifier = [self identifierFromID:item_id type:type];
}
if (identifier) {
[self addNonDefaultTouchBarItems:{ item }];
[self addNonDefaultTouchBarItems:{item}];
touchBar.escapeKeyReplacementItemIdentifier = identifier;
} else {
touchBar.escapeKeyReplacementItemIdentifier = nil;
@ -165,14 +184,16 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
- (void)refreshTouchBarItem:(NSTouchBar*)touchBar
id:(const std::string&)item_id {
if (![self hasItemWithID:item_id]) return;
if (![self hasItemWithID:item_id])
return;
mate::PersistentDictionary settings = settings_[item_id];
std::string item_type;
settings.Get("type", &item_type);
auto identifier = [self identifierFromID:item_id type:item_type];
if (!identifier) return;
if (!identifier)
return;
std::vector<mate::Dictionary> parents;
settings.Get("_parents", &parents);
@ -182,18 +203,19 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
if (!parent.Get("type", &parent_type) || !parent.Get("id", &parent_id))
continue;
auto parentIdentifier = [self identifierFromID:parent_id type:parent_type];
if (!parentIdentifier) continue;
if (!parentIdentifier)
continue;
if (parent_type == "popover") {
NSPopoverTouchBarItem* popoverItem =
[touchBar itemForIdentifier:parentIdentifier];
[touchBar itemForIdentifier:parentIdentifier];
[self refreshTouchBarItem:popoverItem.popoverTouchBar
id:identifier
withType:item_type
withSettings:settings];
id:identifier
withType:item_type
withSettings:settings];
} else if (parent_type == "group") {
NSGroupTouchBarItem* groupItem =
[touchBar itemForIdentifier:parentIdentifier];
[touchBar itemForIdentifier:parentIdentifier];
[self refreshTouchBarItem:groupItem.groupTouchBar
id:identifier
withType:item_type
@ -208,15 +230,16 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
}
- (void)buttonAction:(id)sender {
NSString* item_id = [NSString stringWithFormat:@"%ld", ((NSButton*)sender).tag];
NSString* item_id =
[NSString stringWithFormat:@"%ld", ((NSButton*)sender).tag];
window_->NotifyTouchBarItemInteraction([item_id UTF8String],
base::DictionaryValue());
}
- (void)colorPickerAction:(id)sender {
NSString* identifier = ((NSColorPickerTouchBarItem*)sender).identifier;
NSString* item_id = [self idFromIdentifier:identifier
withPrefix:ColorPickerIdentifier];
NSString* item_id =
[self idFromIdentifier:identifier withPrefix:ColorPickerIdentifier];
NSColor* color = ((NSColorPickerTouchBarItem*)sender).color;
std::string hex_color = atom::ToRGBHex(skia::NSDeviceColorToSkColor(color));
base::DictionaryValue details;
@ -226,8 +249,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
- (void)sliderAction:(id)sender {
NSString* identifier = ((NSSliderTouchBarItem*)sender).identifier;
NSString* item_id = [self idFromIdentifier:identifier
withPrefix:SliderIdentifier];
NSString* item_id =
[self idFromIdentifier:identifier withPrefix:SliderIdentifier];
base::DictionaryValue details;
details.SetInteger("value",
[((NSSliderTouchBarItem*)sender).slider intValue]);
@ -235,31 +258,41 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
}
- (NSString*)idFromIdentifier:(NSString*)identifier
withPrefix:(NSString*)prefix {
withPrefix:(NSString*)prefix {
return [identifier substringFromIndex:[prefix length]];
}
- (void)segmentedControlAction:(id)sender {
NSString* item_id = [NSString stringWithFormat:@"%ld", ((NSSegmentedControl*)sender).tag];
NSString* item_id =
[NSString stringWithFormat:@"%ld", ((NSSegmentedControl*)sender).tag];
base::DictionaryValue details;
details.SetInteger("selectedIndex", ((NSSegmentedControl*)sender).selectedSegment);
details.SetBoolean("isSelected", [((NSSegmentedControl*)sender) isSelectedForSegment:((NSSegmentedControl*)sender).selectedSegment]);
window_->NotifyTouchBarItemInteraction([item_id UTF8String],
details);
details.SetInteger("selectedIndex",
((NSSegmentedControl*)sender).selectedSegment);
details.SetBoolean(
"isSelected",
[((NSSegmentedControl*)sender)
isSelectedForSegment:((NSSegmentedControl*)sender).selectedSegment]);
window_->NotifyTouchBarItemInteraction([item_id UTF8String], details);
}
- (void)scrubber:(NSScrubber*)scrubber didSelectItemAtIndex:(NSInteger)selectedIndex API_AVAILABLE(macosx(10.12.2)) {
- (void)scrubber:(NSScrubber*)scrubber
didSelectItemAtIndex:(NSInteger)selectedIndex
API_AVAILABLE(macosx(10.12.2)) {
base::DictionaryValue details;
details.SetInteger("selectedIndex", selectedIndex);
details.SetString("type", "select");
window_->NotifyTouchBarItemInteraction([scrubber.identifier UTF8String], details);
window_->NotifyTouchBarItemInteraction([scrubber.identifier UTF8String],
details);
}
- (void)scrubber:(NSScrubber*)scrubber didHighlightItemAtIndex:(NSInteger)highlightedIndex API_AVAILABLE(macosx(10.12.2)) {
- (void)scrubber:(NSScrubber*)scrubber
didHighlightItemAtIndex:(NSInteger)highlightedIndex
API_AVAILABLE(macosx(10.12.2)) {
base::DictionaryValue details;
details.SetInteger("highlightedIndex", highlightedIndex);
details.SetString("type", "highlight");
window_->NotifyTouchBarItemInteraction([scrubber.identifier UTF8String], details);
window_->NotifyTouchBarItemInteraction([scrubber.identifier UTF8String],
details);
}
- (NSTouchBarItemIdentifier)identifierFromID:(const std::string&)item_id
@ -300,7 +333,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
- (NSTouchBarItem*)makeButtonForID:(NSString*)id
withIdentifier:(NSString*)identifier {
std::string s_id([id UTF8String]);
if (![self hasItemWithID:s_id]) return nil;
if (![self hasItemWithID:s_id])
return nil;
mate::PersistentDictionary settings = settings_[s_id];
base::scoped_nsobject<NSCustomTouchBarItem> item([[NSClassFromString(
@ -346,7 +380,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
- (NSTouchBarItem*)makeLabelForID:(NSString*)id
withIdentifier:(NSString*)identifier {
std::string s_id([id UTF8String]);
if (![self hasItemWithID:s_id]) return nil;
if (![self hasItemWithID:s_id])
return nil;
mate::PersistentDictionary settings = settings_[s_id];
base::scoped_nsobject<NSCustomTouchBarItem> item([[NSClassFromString(
@ -375,11 +410,12 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
- (NSTouchBarItem*)makeColorPickerForID:(NSString*)id
withIdentifier:(NSString*)identifier {
std::string s_id([id UTF8String]);
if (![self hasItemWithID:s_id]) return nil;
if (![self hasItemWithID:s_id])
return nil;
mate::PersistentDictionary settings = settings_[s_id];
base::scoped_nsobject<NSColorPickerTouchBarItem> item([[NSClassFromString(
@"NSColorPickerTouchBarItem") alloc] initWithIdentifier:identifier]);
@"NSColorPickerTouchBarItem") alloc] initWithIdentifier:identifier]);
[item setTarget:self];
[item setAction:@selector(colorPickerAction:)];
[self updateColorPicker:item withSettings:settings];
@ -390,13 +426,14 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
withSettings:(const mate::PersistentDictionary&)settings {
std::vector<std::string> colors;
if (settings.Get("availableColors", &colors) && !colors.empty()) {
NSColorList* color_list = [[[NSColorList alloc] initWithName:@""] autorelease];
NSColorList* color_list =
[[[NSColorList alloc] initWithName:@""] autorelease];
for (size_t i = 0; i < colors.size(); ++i) {
[color_list insertColor:[self colorFromHexColorString:colors[i]]
key:base::SysUTF8ToNSString(colors[i])
atIndex:i];
}
item.colorList = color_list;
item.colorList = color_list;
}
std::string selectedColor;
@ -408,7 +445,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
- (NSTouchBarItem*)makeSliderForID:(NSString*)id
withIdentifier:(NSString*)identifier {
std::string s_id([id UTF8String]);
if (![self hasItemWithID:s_id]) return nil;
if (![self hasItemWithID:s_id])
return nil;
mate::PersistentDictionary settings = settings_[s_id];
base::scoped_nsobject<NSSliderTouchBarItem> item([[NSClassFromString(
@ -440,7 +478,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
- (NSTouchBarItem*)makePopoverForID:(NSString*)id
withIdentifier:(NSString*)identifier {
std::string s_id([id UTF8String]);
if (![self hasItemWithID:s_id]) return nil;
if (![self hasItemWithID:s_id])
return nil;
mate::PersistentDictionary settings = settings_[s_id];
base::scoped_nsobject<NSPopoverTouchBarItem> item([[NSClassFromString(
@ -467,59 +506,72 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
mate::PersistentDictionary child;
std::vector<mate::PersistentDictionary> items;
if (settings.Get("child", &child) && child.Get("ordereredItems", &items)) {
item.popoverTouchBar = [self touchBarFromItemIdentifiers:[self identifiersFromSettings:items]];
item.popoverTouchBar =
[self touchBarFromItemIdentifiers:[self identifiersFromSettings:items]];
}
}
- (NSTouchBarItem*)makeGroupForID:(NSString*)id
withIdentifier:(NSString*)identifier {
std::string s_id([id UTF8String]);
if (![self hasItemWithID:s_id]) return nil;
if (![self hasItemWithID:s_id])
return nil;
mate::PersistentDictionary settings = settings_[s_id];
mate::PersistentDictionary child;
if (!settings.Get("child", &child)) return nil;
if (!settings.Get("child", &child))
return nil;
std::vector<mate::PersistentDictionary> items;
if (!child.Get("ordereredItems", &items)) return nil;
if (!child.Get("ordereredItems", &items))
return nil;
NSMutableArray* generatedItems = [NSMutableArray array];
NSMutableArray* identifiers = [self identifiersFromSettings:items];
for (NSUInteger i = 0; i < [identifiers count]; ++i) {
if ([identifiers objectAtIndex:i] != NSTouchBarItemIdentifierOtherItemsProxy) {
NSTouchBarItem* generatedItem = [self makeItemForIdentifier:[identifiers objectAtIndex:i]];
if ([identifiers objectAtIndex:i] !=
NSTouchBarItemIdentifierOtherItemsProxy) {
NSTouchBarItem* generatedItem =
[self makeItemForIdentifier:[identifiers objectAtIndex:i]];
if (generatedItem) {
[generatedItems addObject:generatedItem];
}
}
}
return [NSClassFromString(@"NSGroupTouchBarItem") groupItemWithIdentifier:identifier
items:generatedItems];
return [NSClassFromString(@"NSGroupTouchBarItem")
groupItemWithIdentifier:identifier
items:generatedItems];
}
- (void)updateGroup:(NSGroupTouchBarItem*)item
withSettings:(const mate::PersistentDictionary&)settings API_AVAILABLE(macosx(10.12.2)) {
withSettings:(const mate::PersistentDictionary&)settings
API_AVAILABLE(macosx(10.12.2)) {
mate::PersistentDictionary child;
if (!settings.Get("child", &child)) return;
if (!settings.Get("child", &child))
return;
std::vector<mate::PersistentDictionary> items;
if (!child.Get("ordereredItems", &items)) return;
if (!child.Get("ordereredItems", &items))
return;
item.groupTouchBar = [self touchBarFromItemIdentifiers:[self identifiersFromSettings:items]];
item.groupTouchBar =
[self touchBarFromItemIdentifiers:[self identifiersFromSettings:items]];
}
- (NSTouchBarItem*)makeSegmentedControlForID:(NSString*)id
withIdentifier:(NSString*)identifier API_AVAILABLE(macosx(10.12.2)) {
withIdentifier:(NSString*)identifier
API_AVAILABLE(macosx(10.12.2)) {
std::string s_id([id UTF8String]);
if (![self hasItemWithID:s_id]) return nil;
if (![self hasItemWithID:s_id])
return nil;
mate::PersistentDictionary settings = settings_[s_id];
base::scoped_nsobject<NSCustomTouchBarItem> item([[NSClassFromString(
@"NSCustomTouchBarItem") alloc] initWithIdentifier:identifier]);
NSSegmentedControl* control = [NSSegmentedControl segmentedControlWithLabels:[NSMutableArray array]
trackingMode:NSSegmentSwitchTrackingSelectOne
target:self
action:@selector(segmentedControlAction:)];
NSSegmentedControl* control = [NSSegmentedControl
segmentedControlWithLabels:[NSMutableArray array]
trackingMode:NSSegmentSwitchTrackingSelectOne
target:self
action:@selector(segmentedControlAction:)];
control.tag = [id floatValue];
[item setView:control];
@ -528,8 +580,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
}
- (void)updateSegmentedControl:(NSCustomTouchBarItem*)item
withSettings:(const mate::PersistentDictionary&)settings API_AVAILABLE(macosx(10.12.2)) {
withSettings:(const mate::PersistentDictionary&)settings
API_AVAILABLE(macosx(10.12.2)) {
NSSegmentedControl* control = item.view;
std::string segmentStyle;
@ -585,18 +637,23 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
}
- (NSTouchBarItem*)makeScrubberForID:(NSString*)id
withIdentifier:(NSString*)identifier API_AVAILABLE(macosx(10.12.2)) {
withIdentifier:(NSString*)identifier
API_AVAILABLE(macosx(10.12.2)) {
std::string s_id([id UTF8String]);
if (![self hasItemWithID:s_id]) return nil;
if (![self hasItemWithID:s_id])
return nil;
mate::PersistentDictionary settings = settings_[s_id];
base::scoped_nsobject<NSCustomTouchBarItem> item([[NSClassFromString(
@"NSCustomTouchBarItem") alloc] initWithIdentifier:identifier]);
NSScrubber* scrubber = [[[NSClassFromString(@"NSScrubber") alloc] initWithFrame:NSZeroRect] autorelease];
NSScrubber* scrubber = [[[NSClassFromString(@"NSScrubber") alloc]
initWithFrame:NSZeroRect] autorelease];
[scrubber registerClass:NSClassFromString(@"NSScrubberTextItemView") forItemIdentifier:TextScrubberItemIdentifier];
[scrubber registerClass:NSClassFromString(@"NSScrubberImageItemView") forItemIdentifier:ImageScrubberItemIdentifier];
[scrubber registerClass:NSClassFromString(@"NSScrubberTextItemView")
forItemIdentifier:TextScrubberItemIdentifier];
[scrubber registerClass:NSClassFromString(@"NSScrubberImageItemView")
forItemIdentifier:ImageScrubberItemIdentifier];
scrubber.delegate = self;
scrubber.dataSource = self;
@ -609,7 +666,8 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
}
- (void)updateScrubber:(NSCustomTouchBarItem*)item
withSettings:(const mate::PersistentDictionary&)settings API_AVAILABLE(macosx(10.12.2)) {
withSettings:(const mate::PersistentDictionary&)settings
API_AVAILABLE(macosx(10.12.2)) {
NSScrubber* scrubber = item.view;
bool showsArrowButtons = false;
@ -622,17 +680,21 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
settings.Get("overlayStyle", &overlayStyle);
if (selectedStyle == "outline") {
scrubber.selectionBackgroundStyle = [NSClassFromString(@"NSScrubberSelectionStyle") outlineOverlayStyle];
scrubber.selectionBackgroundStyle =
[NSClassFromString(@"NSScrubberSelectionStyle") outlineOverlayStyle];
} else if (selectedStyle == "background") {
scrubber.selectionBackgroundStyle = [NSClassFromString(@"NSScrubberSelectionStyle") roundedBackgroundStyle];
scrubber.selectionBackgroundStyle =
[NSClassFromString(@"NSScrubberSelectionStyle") roundedBackgroundStyle];
} else {
scrubber.selectionBackgroundStyle = nil;
}
if (overlayStyle == "outline") {
scrubber.selectionOverlayStyle = [NSClassFromString(@"NSScrubberSelectionStyle") outlineOverlayStyle];
scrubber.selectionOverlayStyle =
[NSClassFromString(@"NSScrubberSelectionStyle") outlineOverlayStyle];
} else if (overlayStyle == "background") {
scrubber.selectionOverlayStyle = [NSClassFromString(@"NSScrubberSelectionStyle") roundedBackgroundStyle];
scrubber.selectionOverlayStyle =
[NSClassFromString(@"NSScrubberSelectionStyle") roundedBackgroundStyle];
} else {
scrubber.selectionOverlayStyle = nil;
}
@ -652,9 +714,11 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
[scrubber reloadData];
}
- (NSInteger)numberOfItemsForScrubber:(NSScrubber*)scrubber API_AVAILABLE(macosx(10.12.2)) {
- (NSInteger)numberOfItemsForScrubber:(NSScrubber*)scrubber
API_AVAILABLE(macosx(10.12.2)) {
std::string s_id([[scrubber identifier] UTF8String]);
if (![self hasItemWithID:s_id]) return 0;
if (![self hasItemWithID:s_id])
return 0;
mate::PersistentDictionary settings = settings_[s_id];
std::vector<mate::PersistentDictionary> items;
@ -663,15 +727,19 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
}
- (NSScrubberItemView*)scrubber:(NSScrubber*)scrubber
viewForItemAtIndex:(NSInteger)index API_AVAILABLE(macosx(10.12.2)) {
viewForItemAtIndex:(NSInteger)index
API_AVAILABLE(macosx(10.12.2)) {
std::string s_id([[scrubber identifier] UTF8String]);
if (![self hasItemWithID:s_id]) return nil;
if (![self hasItemWithID:s_id])
return nil;
mate::PersistentDictionary settings = settings_[s_id];
std::vector<mate::PersistentDictionary> items;
if (!settings.Get("items", &items)) return nil;
if (!settings.Get("items", &items))
return nil;
if (index >= static_cast<NSInteger>(items.size())) return nil;
if (index >= static_cast<NSInteger>(items.size()))
return nil;
mate::PersistentDictionary item = items[index];
@ -679,13 +747,14 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
std::string title;
if (item.Get("label", &title)) {
NSScrubberTextItemView* view = [scrubber makeItemWithIdentifier:TextScrubberItemIdentifier
owner:self];
NSScrubberTextItemView* view =
[scrubber makeItemWithIdentifier:TextScrubberItemIdentifier owner:self];
view.title = base::SysUTF8ToNSString(title);
itemView = view;
} else {
NSScrubberImageItemView* view = [scrubber makeItemWithIdentifier:ImageScrubberItemIdentifier
owner:self];
NSScrubberImageItemView* view =
[scrubber makeItemWithIdentifier:ImageScrubberItemIdentifier
owner:self];
gfx::Image image;
if (item.Get("icon", &image)) {
view.image = image.AsNSImage();
@ -696,30 +765,38 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item";
return itemView;
}
- (NSSize)scrubber:(NSScrubber *)scrubber layout:(NSScrubberFlowLayout *)layout sizeForItemAtIndex:(NSInteger)itemIndex
API_AVAILABLE(macosx(10.12.2)) {
- (NSSize)scrubber:(NSScrubber*)scrubber
layout:(NSScrubberFlowLayout*)layout
sizeForItemAtIndex:(NSInteger)itemIndex API_AVAILABLE(macosx(10.12.2)) {
NSInteger width = 50;
NSInteger height = 30;
NSInteger margin = 15;
NSSize defaultSize = NSMakeSize(width, height);
std::string s_id([[scrubber identifier] UTF8String]);
if (![self hasItemWithID:s_id]) return defaultSize;
if (![self hasItemWithID:s_id])
return defaultSize;
mate::PersistentDictionary settings = settings_[s_id];
std::vector<mate::PersistentDictionary> items;
if (!settings.Get("items", &items)) return defaultSize;
if (!settings.Get("items", &items))
return defaultSize;
if (itemIndex >= static_cast<NSInteger>(items.size())) return defaultSize;
if (itemIndex >= static_cast<NSInteger>(items.size()))
return defaultSize;
mate::PersistentDictionary item = items[itemIndex];
std::string title;
if (item.Get("label", &title)) {
NSSize size = NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX);
NSRect textRect = [base::SysUTF8ToNSString(title) boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:@{ NSFontAttributeName: [NSFont systemFontOfSize:0]}];
NSRect textRect = [base::SysUTF8ToNSString(title)
boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:@{
NSFontAttributeName : [NSFont systemFontOfSize:0]
}];
width = textRect.size.width + margin;
} else {

View file

@ -9,11 +9,9 @@
namespace atom {
ViewsDelegateMac::ViewsDelegateMac() {
}
ViewsDelegateMac::ViewsDelegateMac() {}
ViewsDelegateMac::~ViewsDelegateMac() {
}
ViewsDelegateMac::~ViewsDelegateMac() {}
void ViewsDelegateMac::OnBeforeWidgetInit(
views::Widget::InitParams* params,