//
//  ViewController.m
//  cbase
//
//  Created by Quanlong He on 9/2/13.
//  Copyright (c) 2013 Quanlong He. All rights reserved.
//

#import "ViewController.h"

#include "chromium/base/bind.h"
#include "chromium/base/memory/scoped_ptr.h"
#include "chromium/base/message_loop/message_loop.h"

void DoSomething() {
  DVLOG(0) << "Print in callback";
}

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

  base::MessageLoopForUI* message_loop = new base::MessageLoopForUI;
  message_loop->Attach();
  base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&DoSomething));
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Fix compiling error of dummy.

//
//  ViewController.m
//  cbase
//
//  Created by Quanlong He on 9/2/13.
//  Copyright (c) 2013 Quanlong He. All rights reserved.
//

#import "ViewController.h"

#include "chromium/base/bind.h"
#include "chromium/base/memory/scoped_ptr.h"
#include "chromium/base/message_loop.h"

void DoSomething() {
  DVLOG(0) << "Print in callback";
}

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

  base::MessageLoopForUI* message_loop = new base::MessageLoopForUI;
  message_loop->Attach();
  base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&DoSomething));
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


#import "sys/rand.hpp"
#import "sys/path_posix.hpp"
#import "sys/clock.hpp"
#import <getopt.h>

bool gEditor;

static void init(int argc, char *argv[])
{
    int opt;
    const char *altpath = NULL;

    while ((opt = getopt(argc, argv, "ei:")) != -1) {
        switch (opt) {
        case 'e':
            gEditor = true;
            break;

        case 'i':
            altpath = optarg;
            break;

        default:
            fputs("Invalid usage\n", stderr);
            exit(1);
        }
    }

    pathInit(altpath);
    initTime();
    Rand::global.seed();
}

int main(int argc, const char *argv[])
{
    init(argc, (char **) argv);
    return NSApplicationMain(argc, argv);
}

Disable strict command line parsing on Mac

#import "sys/rand.hpp"
#import "sys/path_posix.hpp"
#import "sys/clock.hpp"
#import <getopt.h>

bool gEditor;

static void init(int argc, char *argv[])
{
    int opt;
    const char *altpath = NULL;

    while ((opt = getopt(argc, argv, "ei:")) != -1) {
        switch (opt) {
        case 'e':
            gEditor = true;
            break;

        case 'i':
            altpath = optarg;
            break;

        default:
            goto stop;
        }
    }
stop:

    pathInit(altpath);
    initTime();
    Rand::global.seed();
}

int main(int argc, const char *argv[])
{
    init(argc, (char **) argv);
    return NSApplicationMain(argc, argv);
}


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "SearchMenuResultsSpinner.h"

const float SpinnerPeriod = 2.0f;

@interface SearchMenuResultsSpinner()
{
    BOOL isAnimating;
}

@end

@implementation SearchMenuResultsSpinner

- (id)init
{
    const float size = 24.0f;

    [self initWithImage:[UIImage imageNamed:@"search_results_spinner"]];

    self.frame = CGRectMake(0.0f,
                            0.0f,
                            size,
                            size);

    isAnimating = NO;
    self.hidden = YES;

    return self;
}

- (void)startAnimating
{
    isAnimating = YES;
    self.hidden = NO;

    [self animate];
}

- (void)stopAnimating
{
    isAnimating = NO;
    self.hidden = YES;
}

- (void)animate
{
    // adds a 90 degree rotation
    [UIView animateWithDuration: SpinnerPeriod / 4.0f
                          delay: 0.0f
                        options: UIViewAnimationOptionCurveLinear
                     animations: ^{
                         self.transform = CGAffineTransformRotate(self.transform, static_cast<float>(M_PI / 2.0));
                     }
                     completion: ^(BOOL finished){
                         if (finished)
                         {
                             if (isAnimating)
                             {
                                 [self animate];
                             }
                         }
                     }];
}

@end

Fix for MPLY-6742. Search spinner shouldn't increment speed when performing multiple searches. Buddy: Judith

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "SearchMenuResultsSpinner.h"

const float SpinnerPeriod = 2.0f;

@interface SearchMenuResultsSpinner()
{
    BOOL isAnimating;
}

@end

@implementation SearchMenuResultsSpinner

- (id)init
{
    const float size = 24.0f;

    [self initWithImage:[UIImage imageNamed:@"search_results_spinner"]];

    self.frame = CGRectMake(0.0f,
                            0.0f,
                            size,
                            size);

    isAnimating = NO;
    self.hidden = YES;

    return self;
}

- (void)startAnimating
{
    [self stopAnimating];

    isAnimating = YES;
    self.hidden = NO;

    [self animate];
}

- (void)stopAnimating
{
    isAnimating = NO;
    self.hidden = YES;

    [self.layer removeAllAnimations];
}

- (void)animate
{
    // adds a 90 degree rotation
    [UIView animateWithDuration: SpinnerPeriod / 4.0f
                          delay: 0.0f
                        options: UIViewAnimationOptionCurveLinear
                     animations: ^{
                         self.transform = CGAffineTransformRotate(self.transform, static_cast<float>(M_PI / 2.0));
                     }
                     completion: ^(BOOL finished){
                         if (finished)
                         {
                             if (isAnimating)
                             {
                                 [self animate];
                             }
                         }
                     }];
}

@end


//
//  AWCameraCtrl.m
//  SmartOrganizer
//
//  Created by iwat on 11/10/15.
//  Copyright © 2015 AuthorWise. All rights reserved.
//

#import <opencv2/highgui/ios.h>

#import "CVWrapper.h"

#import "AWCameraCtrl.h"

@interface AWCameraCtrl () <CvVideoCameraDelegate>
@end

@implementation AWCameraCtrl {
	CvVideoCamera *videoCamera;
}

#pragma mark - UIViewController

- (void)viewDidLoad {
	[super viewDidLoad];

	videoCamera = [[CvVideoCamera alloc] initWithParentView:self.imageView];
	videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack;
	videoCamera.defaultAVCaptureSessionPreset = AVCaptureSessionPreset352x288;
	videoCamera.defaultAVCaptureVideoOrientation = AVCaptureVideoOrientationPortrait;
	videoCamera.defaultFPS = 30;
	videoCamera.delegate = self;
	videoCamera.grayscaleMode = NO;
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	[videoCamera start];
}

#pragma mark - CvVideoCameraDelegate

- (void)processImage:(cv::Mat &)image {
	self.imageView.image = [CVWrapper debugDrawLargestBlobWithMat:image edges:4];
}

@end

Adjust capture preset for more accuracy

//
//  AWCameraCtrl.m
//  SmartOrganizer
//
//  Created by iwat on 11/10/15.
//  Copyright © 2015 AuthorWise. All rights reserved.
//

#import <opencv2/highgui/ios.h>

#import "CVWrapper.h"

#import "AWCameraCtrl.h"

@interface AWCameraCtrl () <CvVideoCameraDelegate>
@end

@implementation AWCameraCtrl {
	CvVideoCamera *videoCamera;
}

#pragma mark - UIViewController

- (void)viewDidLoad {
	[super viewDidLoad];

	videoCamera = [[CvVideoCamera alloc] initWithParentView:self.imageView];
	videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack;
	videoCamera.defaultAVCaptureSessionPreset = AVCaptureSessionPreset1280x720;
	videoCamera.defaultAVCaptureVideoOrientation = AVCaptureVideoOrientationPortrait;
	videoCamera.defaultFPS = 30;
	videoCamera.delegate = self;
	videoCamera.grayscaleMode = NO;
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	[videoCamera start];
}

#pragma mark - CvVideoCameraDelegate

- (void)processImage:(cv::Mat &)image {
	self.imageView.image = [CVWrapper debugDrawLargestBlobWithMat:image edges:4];
}

@end


// RUN: %clang_cc1 -fsyntax-only -verify -Wno-objc-root-class %s
// rdar://12095239
// rdar://14261999

class CppAbstractBase {
public:
    virtual void testA() = 0;
    virtual void testB() = 0; // expected-note {{unimplemented pure virtual method 'testB' in 'CppConcreteSub}}
    int a;
};

class CppConcreteSub : public CppAbstractBase {
    virtual void testA() { }
};

@interface Objc  {
    CppConcreteSub _concrete; // expected-error{{instance variable type 'CppConcreteSub' is an abstract class}}
}
- (CppAbstractBase*)abstract;
@property (nonatomic, readonly) const CppConcreteSub& Prop;  // expected-note {{property declared here}}
@end

@implementation Objc
- (CppAbstractBase*)abstract {
    return &_concrete;
}
@synthesize Prop; // expected-error {{synthesized instance variable type 'const CppConcreteSub' is an abstract class}}
@end

class Cpp {
public:
    CppConcreteSub sub; // expected-error {{field type 'CppConcreteSub' is an abstract class}}
};

Remove referece type onproperty of abstract class type. // rdar://14261999

// RUN: %clang_cc1 -fsyntax-only -verify -Wno-objc-root-class %s
// rdar://12095239
// rdar://14261999

class CppAbstractBase {
public:
    virtual void testA() = 0;
    virtual void testB() = 0; // expected-note {{unimplemented pure virtual method 'testB' in 'CppConcreteSub}}
    int a;
};

class CppConcreteSub : public CppAbstractBase {
    virtual void testA() { }
};

@interface Objc  {
    CppConcreteSub _concrete; // expected-error{{instance variable type 'CppConcreteSub' is an abstract class}}
}
- (CppAbstractBase*)abstract;
@property (nonatomic, readonly) const CppConcreteSub Prop;  // expected-note {{property declared here}}
@end

@implementation Objc
- (CppAbstractBase*)abstract {
    return &_concrete;
}
@synthesize Prop; // expected-error {{synthesized instance variable type 'const CppConcreteSub' is an abstract class}}
@end

class Cpp {
public:
    CppConcreteSub sub; // expected-error {{field type 'CppConcreteSub' is an abstract class}}
};


// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 %s

class C {

  void f() {
    int foo, bar;

    // fail to parse as a lambda introducer, so we get objc message parsing errors instead
    [foo,+] {}; // expected-error {{expected expression}}

    []; // expected-error {{expected body of lambda expression}}
    [=,foo+] {}; // expected-error {{expected ',' or ']' in lambda capture list}}
    [&this] {}; // expected-error {{address expression must be an lvalue}}
    [] {}; // expected-error {{lambda expressions are not supported yet}}
    [=] (int i) {}; // expected-error {{lambda expressions are not supported yet}}
    [&] (int) mutable -> void {}; // expected-error {{lambda expressions are not supported yet}}
    [foo,bar] () { return 3; }; // expected-error {{lambda expressions are not supported yet}}
    [=,&foo] () {}; // expected-error {{lambda expressions are not supported yet}}
    [this] () {}; // expected-error {{lambda expressions are not supported yet}}
  }

};

Fix yet one more test

// RUN: %clang_cc1 -fsyntax-only -verify -Wno-unused-value -std=c++11 %s

class C {

  void f() {
    int foo, bar;

    // fail to parse as a lambda introducer, so we get objc message parsing errors instead
    [foo,+] {}; // expected-error {{expected expression}}

    []; // expected-error {{expected body of lambda expression}}
    [=,foo+] {}; // expected-error {{expected ',' or ']' in lambda capture list}}
    [&this] {}; // expected-error {{address expression must be an lvalue}}
    [] {}; // expected-error {{lambda expressions are not supported yet}}
    [=] (int i) {}; // expected-error {{lambda expressions are not supported yet}}
    [&] (int) mutable -> void {}; // expected-error {{lambda expressions are not supported yet}}
    [foo,bar] () { return 3; }; // expected-error {{lambda expressions are not supported yet}}
    [=,&foo] () {}; // expected-error {{lambda expressions are not supported yet}}
    [this] () {}; // expected-error {{lambda expressions are not supported yet}}
  }

};


/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#import <Cocoa/Cocoa.h>

// FIXME: should be in a header
void setSystemPreferences();

void setSystemPreferences() {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Set LCD font smoothing level for this application (does not affect other
    // applications). Based on resetDefaultsToConsistentValues() in
    // http://trac.webkit.org/browser/trunk/Tools/DumpRenderTree/mac/DumpRenderTree.mm
    enum {
        NoFontSmoothing     = 0,
        LightFontSmoothing  = 1,
        MediumFontSmoothing = 2,
        StrongFontSmoothing = 3,
    };
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:MediumFontSmoothing forKey:@"AppleFontSmoothing"];

    [pool release];
}

Include system_preferences.h in mac file.

/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "system_preferences.h"

#import <Cocoa/Cocoa.h>

void setSystemPreferences() {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Set LCD font smoothing level for this application (does not affect other
    // applications). Based on resetDefaultsToConsistentValues() in
    // http://trac.webkit.org/browser/trunk/Tools/DumpRenderTree/mac/DumpRenderTree.mm
    enum {
        NoFontSmoothing     = 0,
        LightFontSmoothing  = 1,
        MediumFontSmoothing = 2,
        StrongFontSmoothing = 3,
    };
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:MediumFontSmoothing forKey:@"AppleFontSmoothing"];

    [pool release];
}


#import <Foundation/Foundation.h>

#define PREFERENCES_FILE @"/var/mobile/Library/Preferences/net.howett.safaridownloader.plist"

extern "C" BOOL isCapable() {
 	return YES;
}

extern "C" BOOL isEnabled() {
	NSDictionary *userPrefs = [NSDictionary dictionaryWithContentsOfFile:PREFERENCES_FILE];
	BOOL disabled = [[userPrefs objectForKey:@"Disabled"] boolValue];
	return !disabled;
}

extern "C" float getDelayTime() { return 1.0f; }

extern "C" void setState(BOOL enabled) {
	BOOL disabled = !enabled;
	NSMutableDictionary *userPrefs = [NSMutableDictionary dictionaryWithContentsOfFile:PREFERENCES_FILE];
	[userPrefs setValue:[NSNumber numberWithBool:disabled] forKey:@"Disabled"];
	[userPrefs writeToFile:PREFERENCES_FILE atomically:NO];
	CFNotificationCenterRef r = CFNotificationCenterGetDarwinNotifyCenter();
	CFNotificationCenterPostNotification(r, CFSTR("net.howett.safaridownloader/ReloadPrefs"), NULL, NULL, true);
	return;
}

Drop the SBSettings button delay time to 0.25 seconds.

#import <Foundation/Foundation.h>

#define PREFERENCES_FILE @"/var/mobile/Library/Preferences/net.howett.safaridownloader.plist"

extern "C" BOOL isCapable() {
 	return YES;
}

extern "C" BOOL isEnabled() {
	NSDictionary *userPrefs = [NSDictionary dictionaryWithContentsOfFile:PREFERENCES_FILE];
	BOOL disabled = [[userPrefs objectForKey:@"Disabled"] boolValue];
	return !disabled;
}

extern "C" float getDelayTime() { return 0.25f; }

extern "C" void setState(BOOL enabled) {
	BOOL disabled = !enabled;
	NSMutableDictionary *userPrefs = [NSMutableDictionary dictionaryWithContentsOfFile:PREFERENCES_FILE];
	[userPrefs setValue:[NSNumber numberWithBool:disabled] forKey:@"Disabled"];
	[userPrefs writeToFile:PREFERENCES_FILE atomically:NO];
	CFNotificationCenterRef r = CFNotificationCenterGetDarwinNotifyCenter();
	CFNotificationCenterPostNotification(r, CFSTR("net.howett.safaridownloader/ReloadPrefs"), NULL, NULL, true);
	return;
}


// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util.h"

#import <Cocoa/Cocoa.h>
#include <copyfile.h>

#include "base/basictypes.h"
#include "base/file_path.h"
#include "base/string_util.h"

namespace file_util {

bool GetTempDir(FilePath* path) {
  NSString* tmp = NSTemporaryDirectory();
  if (tmp == nil)
    return false;
  *path = FilePath([tmp fileSystemRepresentation]);
  return true;
}

bool GetShmemTempDir(FilePath* path) {
  return GetTempDir(path);
}

bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
  return (copyfile(from_path.value().c_str(),
                   to_path.value().c_str(), NULL, COPYFILE_ALL) == 0);
}

}  // namespace

Add AssertIOAllowed() call to CopyFile()

// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util.h"

#import <Cocoa/Cocoa.h>
#include <copyfile.h>

#include "base/basictypes.h"
#include "base/file_path.h"
#include "base/string_util.h"
#include "base/thread_restrictions.h"

namespace file_util {

bool GetTempDir(FilePath* path) {
  NSString* tmp = NSTemporaryDirectory();
  if (tmp == nil)
    return false;
  *path = FilePath([tmp fileSystemRepresentation]);
  return true;
}

bool GetShmemTempDir(FilePath* path) {
  return GetTempDir(path);
}

bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
  base::ThreadRestrictions::AssertIOAllowed();
  return (copyfile(from_path.value().c_str(),
                   to_path.value().c_str(), NULL, COPYFILE_ALL) == 0);
}

}  // namespace


#include "pixelboost/util/localisation/localisation.h"

std::string pb::GetCurrentLocale()
{
    return [[[NSLocale preferredLanguages] objectAtIndex:0] UTF8String];
}


// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "me2me_preference_pane_confirm_pin.h"

@implementation Me2MePreferencePaneConfirmPin

@synthesize delegate = delegate_;

- (id)init {
    self = [super initWithNibName:@"me2me_preference_pane_confirm_pin"
                           bundle:[NSBundle bundleForClass:[self class]]];
    return self;
}

- (void)dealloc {
  [delegate_ release];
  [super dealloc];
}

- (void)setEmail:(NSString*)email {
  [email_ setStringValue:email];
}

- (void)setButtonText:(NSString*)text {
  [apply_button_ setTitle:text];
}

- (void)setEnabled:(BOOL)enabled {
  [apply_button_ setEnabled:enabled];
  [pin_ setEnabled:enabled];
}

- (void)resetPin {
  [pin_ setStringValue:@""];
}

- (void)onApply:(id)sender {
  [delegate_ applyConfiguration:self
                            pin:[pin_ stringValue]];
}

@end

Set focus to PIN entry box in pref-pane

// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "me2me_preference_pane_confirm_pin.h"

@implementation Me2MePreferencePaneConfirmPin

@synthesize delegate = delegate_;

- (id)init {
    self = [super initWithNibName:@"me2me_preference_pane_confirm_pin"
                           bundle:[NSBundle bundleForClass:[self class]]];
    return self;
}

- (void)dealloc {
  [delegate_ release];
  [super dealloc];
}

- (void)setEmail:(NSString*)email {
  [email_ setStringValue:email];
}

- (void)setButtonText:(NSString*)text {
  [apply_button_ setTitle:text];
}

- (void)setEnabled:(BOOL)enabled {
  [apply_button_ setEnabled:enabled];
  [pin_ setEnabled:enabled];
  [[[self view] window] makeFirstResponder:pin_];
  [apply_button_ setKeyEquivalent:@"\r"];
}

- (void)resetPin {
  [pin_ setStringValue:@""];
}

- (void)onApply:(id)sender {
  [delegate_ applyConfiguration:self
                            pin:[pin_ stringValue]];
}

@end


extern "C"{
    void CleanIconBadge_();
    void OpenAppSetting_();
    bool IsNotificationPermitted_();
}

// Clean app icon badge
void CleanIconBadge_(){
    [UIApplication sharedApplication].applicationIconBadgeNumber = -1;
}

// Open app settings (more than ios8.0)
void OpenAppSetting_(){
    float iOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if(iOSVersion >= 8.0){
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url];
    }
}

// Check if notification is permitted by user (Always return true if version is less than 8.0)
bool IsNotificationPermitted_(){
    float iOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if(iOSVersion < 8.0){
        return true;
    }
    return [[UIApplication sharedApplication] isRegisteredForRemoteNotifications];
}

Edit ios plugin notification permitted func

extern "C"{
    void CleanIconBadge_();
    void OpenAppSetting_();
    bool IsNotificationPermitted_();
}

// Clean app icon badge
void CleanIconBadge_(){
    [UIApplication sharedApplication].applicationIconBadgeNumber = -1;
}

// Open app settings (more than ios8.0)
void OpenAppSetting_(){
    float iOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if(iOSVersion >= 8.0){
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url];
    }
}

// Check if notification is permitted by user (Always return true if version is less than 8.0)
bool IsNotificationPermitted_(){
    float iOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if(iOSVersion < 8.0){
        return true;
    }
    UIUserNotificationSettings *settings = [[UIApplication sharedApplication] currentUserNotificationSettings];
    return settings.types != 0;
}


Add an ivar test for modern objc abi translator.

// RUN: %clang_cc1 -E %s -o %t.mm
// RUN: %clang_cc1 -x objective-c++ -fblocks -fms-extensions -rewrite-objc %t.mm -o - | FileCheck %s

void *sel_registerName(const char *);

@interface NSMutableArray
- (void)addObject:(id)addObject;
@end

@interface NSInvocation {
@private
    id _container;
}
+ (NSInvocation *)invocationWithMethodSignature;

@end

@implementation NSInvocation

+ (NSInvocation *)invocationWithMethodSignature {
    NSInvocation *newInv;
    id obj = newInv->_container;
    [newInv->_container addObject:0];
   return 0;
}
@end

// CHECK: id obj = (*(id *)((char *)newInv + OBJC_IVAR_$_NSInvocation__container));


Test case for r110459. Radar 8264751. Test case by Fariborz Jahanian!

// RUN: %llvmgcc %s -S -emit-llvm
struct TFENode {
  TFENode(const TFENode& inNode);
};

@interface TIconViewController
- (const TFENode&) target;
@end

void sortAllChildrenForNode(const TFENode&node);

@implementation TIconViewController
- (void) setArrangeBy {
  sortAllChildrenForNode(self.target);
}
@end


// RUN: %clang_cc1 -analyze -analyzer-checker=core -fobjc-arc -cfg-add-implicit-dtors -Wno-null-dereference -verify %s

struct Wrapper {
  __strong id obj;
};

void test() {
  Wrapper w;
  // force a diagnostic
  *(char *)0 = 1; // expected-warning{{Dereference of null pointer}}
}

Add a test for copy-constructor inlining.

// RUN: %clang_cc1 -analyze -analyzer-checker=core,debug.ExprInspection -fobjc-arc -cfg-add-implicit-dtors -Wno-null-dereference -verify %s

void clang_analyzer_eval(bool);

struct Wrapper {
  __strong id obj;
};

void test() {
  Wrapper w;
  // force a diagnostic
  *(char *)0 = 1; // expected-warning{{Dereference of null pointer}}
}

struct IntWrapper {
  int x;
};

void testCopyConstructor() {
  IntWrapper a;
  a.x = 42;

  IntWrapper b(a);
  clang_analyzer_eval(b.x == 42); // expected-warning{{TRUE}}
}

struct NonPODIntWrapper {
  int x;

  virtual int get();
};

void testNonPODCopyConstructor() {
  NonPODIntWrapper a;
  a.x = 42;

  NonPODIntWrapper b(a);
  clang_analyzer_eval(b.x == 42); // expected-warning{{TRUE}}
}


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "DeviceHelpers.h"
#include <algorithm>

namespace ExampleApp
{
    namespace Helpers
    {
        int deviceFramerateWhitelist[] = {
            GAME_DEVICE_IPHONE8_PLUS,
            GAME_DEVICE_IPHONE8,
            GAME_DEVICE_IPADPRO_12_9_INCH,
            GAME_DEVICE_IPADPRO_9_7_INCH,
            GAME_DEVICE_IPHONE_SE,
            GAME_DEVICE_IPHONE7_PLUS,
            GAME_DEVICE_IPHONE7,
            GAME_DEVICE_IPHONE6S_PLUS,
            GAME_DEVICE_IPHONE6S,
            GAME_DEVICE_IPHONE6PLUS,
            GAME_DEVICE_IPHONE6,
            GAME_DEVICE_IPHONE5S,
            GAME_DEVICE_IPOD6GEN,
            GAME_DEVICE_IPADAIR_2,
            GAME_DEVICE_IPADMINI_3,
            GAME_DEVICE_IPADMINI_4
        };

        namespace DeviceHelpers
        {
            NSInteger GetPreferredFramerate(const GameDeviceType& deviceType)
            {
                bool isWhitelisted = std::find(std::begin(deviceFramerateWhitelist), std::end(deviceFramerateWhitelist), deviceType) != std::end(deviceFramerateWhitelist);

                return isWhitelisted ? (NSInteger)60 : (NSInteger)30;
            }
        }
    }
}

Fix for [MPLY-9790]; iOS 60FPS Whitelist is now a 30FPS Blacklist. New devices will no longer need to be added to the list to get the benefit of 60FPS. Buddy: Jonty

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "DeviceHelpers.h"
#include <algorithm>

namespace ExampleApp
{
    namespace Helpers
    {
        int deviceFramerateBlacklist[] = {
            GAME_DEVICE_IPHONE1,
            GAME_DEVICE_IPHONE3G,
            GAME_DEVICE_IPHONE4,
            GAME_DEVICE_IPHONE4S,
            GAME_DEVICE_IPHONE5,
            GAME_DEVICE_IPOD1GEN,
            GAME_DEVICE_IPOD2GEN,
            GAME_DEVICE_IPOD3GEN,
            GAME_DEVICE_IPOD4GEN,
            GAME_DEVICE_IPOD5GEN,
            GAME_DEVICE_IPAD1,
            GAME_DEVICE_IPAD2,
            GAME_DEVICE_IPAD3,
            GAME_DEVICE_IPAD4,
            GAME_DEVICE_IPADAIR,
            GAME_DEVICE_IPADMINI_1GEN,
            GAME_DEVICE_IPADMINI_2
        };

        namespace DeviceHelpers
        {
            NSInteger GetPreferredFramerate(const GameDeviceType& deviceType)
            {
                bool isBlacklisted = std::find(std::begin(deviceFramerateBlacklist), std::end(deviceFramerateBlacklist), deviceType) != std::end(deviceFramerateBlacklist);

                return isBlacklisted ? (NSInteger)30 : (NSInteger)60;
            }
        }
    }
}


// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#import <Cocoa/Cocoa.h>
#include "ApplicationMacOS.h"
#import "AppDelegate.h"

namespace ouzel
{
    ApplicationMacOS::ApplicationMacOS(int aArgc, char* aArgv[]):
        Application(aArgc, aArgv)
    {
        mainQueue = dispatch_get_main_queue();
    }

    int ApplicationMacOS::run()
    {
        @autoreleasepool
        {
            NSApplication* application = [NSApplication sharedApplication];
            [application activateIgnoringOtherApps : YES];

            AppDelegate* appDelegate = [[[AppDelegate alloc] init] autorelease];
            [application setDelegate:appDelegate];
            [application run];
        }

        return EXIT_SUCCESS;
    }

    void ApplicationMacOS::exit()
    {
        Application::exit();

        NSApplication* application = [NSApplication sharedApplication];
        [application terminate:Nil];
    }

    void ApplicationMacOS::execute(const std::function<void(void)>& func)
    {
        std::function<void(void)> localFunction = func;

        dispatch_async(mainQueue, ^{
            localFunction();
        });
    }
}

Exit application on main thread

// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#import <Cocoa/Cocoa.h>
#include "ApplicationMacOS.h"
#import "AppDelegate.h"

namespace ouzel
{
    ApplicationMacOS::ApplicationMacOS(int aArgc, char* aArgv[]):
        Application(aArgc, aArgv)
    {
        mainQueue = dispatch_get_main_queue();
    }

    int ApplicationMacOS::run()
    {
        @autoreleasepool
        {
            NSApplication* application = [NSApplication sharedApplication];
            [application activateIgnoringOtherApps : YES];

            AppDelegate* appDelegate = [[[AppDelegate alloc] init] autorelease];
            [application setDelegate:appDelegate];
            [application run];
        }

        return EXIT_SUCCESS;
    }

    void ApplicationMacOS::exit()
    {
        Application::exit();

        dispatch_async(mainQueue, ^{
            NSApplication* application = [NSApplication sharedApplication];
            [application terminate:Nil];
        });
    }

    void ApplicationMacOS::execute(const std::function<void(void)>& func)
    {
        std::function<void(void)> localFunction = func;

        dispatch_async(mainQueue, ^{
            localFunction();
        });
    }
}


// RUN: %clang_cc1  -Wstrict-selector-match -fsyntax-only -verify %s

#include <objc/objc.h>

@interface Base
- (id) meth1: (Base *)arg1; 	// expected-note {{using}}
- (id) window;	// expected-note {{using}}
@end

@interface Derived: Base
- (id) meth1: (Derived *)arg1;	// expected-note {{also found}}
- (Base *) window;	// expected-note {{also found}}
@end

void foo(void) {
  id r;

  [r meth1:r];	// expected-warning {{multiple methods named 'meth1:' found [-Wstrict-selector-match]}}
  [r window]; 	// expected-warning {{multiple methods named 'window' found [-Wstrict-selector-match]}}
}

Fix test to not depend on objc.h header.

// RUN: %clang_cc1  -Wstrict-selector-match -fsyntax-only -verify %s

@interface Base
- (id) meth1: (Base *)arg1; 	// expected-note {{using}}
- (id) window;	// expected-note {{using}}
@end

@interface Derived: Base
- (id) meth1: (Derived *)arg1;	// expected-note {{also found}}
- (Base *) window;	// expected-note {{also found}}
@end

void foo(void) {
  id r;

  [r meth1:r];	// expected-warning {{multiple methods named 'meth1:' found [-Wstrict-selector-match]}}
  [r window]; 	// expected-warning {{multiple methods named 'window' found [-Wstrict-selector-match]}}
}


Add another test case for r101029, which verifies that we now correctly diagnose instantiation of a function parameter with Objective-C class type (since Objective-C classes can't be passed by value).

// RUN: %clang_cc1 -verify %s

@interface A
@end

template<typename T>
struct X0 {
  void f(T); // expected-error{{interface type 'A' cannot be passed by value}}
};

X0<A> x0a; // expected-note{{instantiation}}


//
// Created by Dawid Drozd aka Gelldur on 6/15/16.
//

#include <component/view/Text.h>

#include <platform/Context.h>
#include <log.h>
#include <ColorUtils.h>

#import <UIKit/UIKit.h>

void Text::setText(const char* text)
{
	auto context = getContext();

	// @formatter:off
	UILabel* label = context->getNative();
	label.text = [NSString stringWithUTF8String:text];
	// @formatter:on
}

void Text::setText(const std::string& text)
{
	setText(text.c_str());
}

void Text::setTextColor(int color)
{
	auto context = getContext();

	UILabel* label = context->getNative();
	label.textColor = UIColorFromRGB(color);
}

Add iOS attributed text implementation

//
// Created by Dawid Drozd aka Gelldur on 6/15/16.
//

#include <component/view/Text.h>

#include <platform/Context.h>
#include <log.h>
#include <ColorUtils.h>
#include <Utils.h>
#include <acme/text/AttributedText.h>

#import <UIKit/UIKit.h>

void Text::setText(const char* text)
{
	auto context = getContext();

	UILabel* label = context->getNative();
	label.text = [NSString stringWithUTF8String:text];
}

void Text::setText(const std::string& text)
{
	setText(text.c_str());
}

void Text::setTextColor(int color)
{
	auto context = getContext();

	UILabel* label = context->getNative();
	label.textColor = UIColorFromRGB(color);
}

void Text::setTextAttributed(const AttributedText& attributedText)
{
	NSMutableAttributedString* attributedString= [[NSMutableAttributedString alloc] initWithString:@""];

	for(auto& element : attributedText.getElements())
	{
		NSAttributedString* attachmentString;
		if(element.type == AttributedText::ElementType::IMAGE_LOCAL)
		{
			NSTextAttachment* attachment = [[NSTextAttachment alloc] init];
            attachment.image = [UIImage imageNamed:stringConvert(element.value)];
            attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];
		}
		else
		{
			attachmentString = [[NSAttributedString alloc] initWithString:stringConvert(element.value)];
		}

		[attributedString appendAttributedString:attachmentString];
	}

	auto context = getContext();

	UILabel* label = context->getNative();
	label.attributedText = attributedString;
}


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import <Cocoa/Cocoa.h>

#include "base/scoped_nsobject.h"
#import "chrome/browser/cocoa/task_manager_mac.h"
#import "chrome/browser/cocoa/cocoa_test_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"

namespace {

class TaskManagerWindowControllerTest : public PlatformTest {
 public:
  TaskManagerWindowControllerTest() {
    controller_.reset([[TaskManagerWindowController alloc] init]);
  }

  scoped_nsobject<TaskManagerWindowController> controller_;
  CocoaTestHelper cocoa_helper_;  // Inits Cocoa, creates window, etc...
};

// Test creation, to ensure nothing leaks or crashes
TEST_F(TaskManagerWindowControllerTest, Init) {
}

// TODO(thakis): Add tests for more methods as they become implemented
// (TaskManager::Show() etc).

}  // namespace

Move TaskManagerMacUnitTest over to Cocoatest.

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import <Cocoa/Cocoa.h>

#include "base/scoped_nsobject.h"
#import "chrome/browser/cocoa/task_manager_mac.h"
#import "chrome/browser/cocoa/cocoa_test_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"

namespace {

class TaskManagerWindowControllerTest : public CocoaTest {
 public:
  virtual void SetUp() {
    CocoaTest::SetUp();
    controller_ = [[TaskManagerWindowController alloc] init];
  }

  virtual void TearDown() {
    [controller_ close];
    CocoaTest::TearDown();
  }

  TaskManagerWindowController *controller_;
};

// Test creation, to ensure nothing leaks or crashes
TEST_F(TaskManagerWindowControllerTest, Init) {
}

// TODO(thakis): Add tests for more methods as they become implemented
// (TaskManager::Show() etc).

}  // namespace


// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/common_web_contents_delegate.h"

#import <Cocoa/Cocoa.h>

#include "brightray/browser/mac/event_dispatching_window.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "ui/events/keycodes/keyboard_codes.h"

@interface NSWindow (EventDispatchingWindow)
- (void)redispatchKeyEvent:(NSEvent*)event;
@end

namespace atom {

void CommonWebContentsDelegate::HandleKeyboardEvent(
    content::WebContents* source,
    const content::NativeWebKeyboardEvent& event) {
  if (event.skip_in_browser ||
      event.type == content::NativeWebKeyboardEvent::Char)
    return;

  // Escape exits tabbed fullscreen mode.
  if (event.windowsKeyCode == ui::VKEY_ESCAPE && is_html_fullscreen())
    ExitFullscreenModeForTab(source);

  // Send the event to the menu before sending it to the window
  if (event.os_event.type == NSKeyDown &&
      [[NSApp mainMenu] performKeyEquivalent:event.os_event])
    return;

  if (event.os_event.window)
    [event.os_event.window redispatchKeyEvent:event.os_event];
}

}  // namespace atom

Check that window is an EventDispatchingWindow

// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/common_web_contents_delegate.h"

#import <Cocoa/Cocoa.h>

#include "brightray/browser/mac/event_dispatching_window.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "ui/events/keycodes/keyboard_codes.h"

@interface NSWindow (EventDispatchingWindow)
- (void)redispatchKeyEvent:(NSEvent*)event;
@end

namespace atom {

void CommonWebContentsDelegate::HandleKeyboardEvent(
    content::WebContents* source,
    const content::NativeWebKeyboardEvent& event) {
  if (event.skip_in_browser ||
      event.type == content::NativeWebKeyboardEvent::Char)
    return;

  // Escape exits tabbed fullscreen mode.
  if (event.windowsKeyCode == ui::VKEY_ESCAPE && is_html_fullscreen())
    ExitFullscreenModeForTab(source);

  // Send the event to the menu before sending it to the window
  if (event.os_event.type == NSKeyDown &&
      [[NSApp mainMenu] performKeyEquivalent:event.os_event])
    return;

  if (event.os_event.window &&
      [event.os_event.window isKindOfClass:[EventDispatchingWindow class]])
    [event.os_event.window redispatchKeyEvent:event.os_event];
}

}  // namespace atom


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser_window.h"
#include "chrome/browser/browser_window_controller.h"

// Create the controller for the Browser, which handles loading the browser
// window from the nib. The controller takes ownership of |browser|.
// static
BrowserWindow* BrowserWindow::CreateBrowserWindow(Browser* browser) {
  // TODO(pinkerton): figure out ownership model. If BrowserList keeps track
  // of the browser windows, it will probably tell us when it needs to go
  // away, and it seems we need to feed back to that when we get a
  // performClose: from the UI.
  BrowserWindowController* controller =
      [[BrowserWindowController alloc] initWithBrowser:browser];
  return [controller browserWindow];
}

Update header ref to new location.

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser_window.h"
#include "chrome/browser/cocoa/browser_window_controller.h"

// Create the controller for the Browser, which handles loading the browser
// window from the nib. The controller takes ownership of |browser|.
// static
BrowserWindow* BrowserWindow::CreateBrowserWindow(Browser* browser) {
  // TODO(pinkerton): figure out ownership model. If BrowserList keeps track
  // of the browser windows, it will probably tell us when it needs to go
  // away, and it seems we need to feed back to that when we get a
  // performClose: from the UI.
  BrowserWindowController* controller =
      [[BrowserWindowController alloc] initWithBrowser:browser];
  return [controller browserWindow];
}


// RUN: %clang_cc1 -x objective-c++ -fblocks -fms-extensions -rewrite-objc -o - %s

extern "C" {
extern "C" void *_Block_copy(const void *aBlock);
extern "C" void _Block_release(const void *aBlock);
}

int main() {
    __attribute__((__blocks__(byref))) int a = 42;
    int save_a = a;

    void (^b)(void) = ^{
        ((__typeof(^{ a = 2; }))_Block_copy((const void *)(^{ a = 2; })));
    };

    ((__typeof(b))_Block_copy((const void *)(b)));

    return 0;
}

Enhance test to check on expected rewritten output.

// RUN: %clang_cc1 -x objective-c++ -fblocks -fms-extensions -rewrite-objc %s -o %t-rw.cpp
// RUN: FileCheck -check-prefix LP --input-file=%t-rw.cpp %s

extern "C" {
extern "C" void *_Block_copy(const void *aBlock);
extern "C" void _Block_release(const void *aBlock);
}

int main() {
    __attribute__((__blocks__(byref))) int a = 42;
    int save_a = a;

    void (^b)(void) = ^{
        ((__typeof(^{ a = 2; }))_Block_copy((const void *)(^{ a = 2; })));
    };

    ((__typeof(b))_Block_copy((const void *)(b)));

    return 0;
}

// CHECK-LP: ((void (^)(void))_Block_copy((const void *)(b)))


#ifdef PIXELBOOST_PLATFORM_OSX

#include <Foundation/Foundation.h>

#include "pixelboost/file/fileHelpers.h"

namespace pb
{

namespace FileHelpers
{

std::string GetRootPath()
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    std::string rootPath = [[[NSBundle mainBundle] resourcePath] UTF8String];
    [pool release];
    return rootPath;
}

std::string GetUserPath()
{
    return "";
}

bool pb::FileHelpers::CreateDirectory(const std::string& directory)
{
    NSString* dirToCreate = [NSString stringWithUTF8String:directory.c_str()];
    NSError* error = nil;
    BOOL isDir=YES;

    if([[NSFileManager defaultManager] fileExistsAtPath:dirToCreate isDirectory:&isDir] || !isDir)
        return false;

    if(![[NSFileManager defaultManager] createDirectoryAtPath:dirToCreate withIntermediateDirectories:YES attributes:nil error:&error])
    {
        return false;
    }

    return true;
}

int pb::FileHelpers::GetTimestamp(const std::string& filename)
{
    NSDictionary* attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithUTF8String:filename.c_str()] error:nil];

    if (attrs != nil)
    {
        NSDate *date = (NSDate*)[attrs objectForKey: NSFileModificationDate];
        return (int)[date timeIntervalSince1970];
    }
    else {
        return 0;
    }
}

}

}

#endif

Fix compilation in XCode 4.6

#ifdef PIXELBOOST_PLATFORM_OSX

#include <Foundation/Foundation.h>

#include "pixelboost/file/fileHelpers.h"

namespace pb
{

namespace FileHelpers
{

std::string GetRootPath()
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    std::string rootPath = [[[NSBundle mainBundle] resourcePath] UTF8String];
    [pool release];
    return rootPath;
}

std::string GetUserPath()
{
    return "";
}

bool CreateDirectory(const std::string& directory)
{
    NSString* dirToCreate = [NSString stringWithUTF8String:directory.c_str()];
    NSError* error = nil;
    BOOL isDir=YES;

    if([[NSFileManager defaultManager] fileExistsAtPath:dirToCreate isDirectory:&isDir] || !isDir)
        return false;

    if(![[NSFileManager defaultManager] createDirectoryAtPath:dirToCreate withIntermediateDirectories:YES attributes:nil error:&error])
    {
        return false;
    }

    return true;
}

int GetTimestamp(const std::string& filename)
{
    NSDictionary* attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithUTF8String:filename.c_str()] error:nil];

    if (attrs != nil)
    {
        NSDate *date = (NSDate*)[attrs objectForKey: NSFileModificationDate];
        return (int)[date timeIntervalSince1970];
    }
    else {
        return 0;
    }
}

}

}

#endif


//
//  BCRocksTests.m
//  BCRocks
//
//  Created by Iska on 15/11/14.
//  Copyright (c) 2014 BrainCookie. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import "RocksDB.h"

@interface BCRocksTests : XCTestCase

@end

@implementation BCRocksTests

- (void)setUp
{
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown
{
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testCompile
{
	RocksDB *rocks = [RocksDB new];

    XCTAssert(YES, @"Pass");
}

@end

Add first test case for put/get data

//
//  BCRocksTests.m
//  BCRocks
//
//  Created by Iska on 15/11/14.
//  Copyright (c) 2014 BrainCookie. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import "BCRocks.h"

@interface BCRocksTests : XCTestCase
{
	RocksDB *_rocks;
}
@end

@implementation BCRocksTests

- (void)setUp
{
	[super setUp];

	NSString * path = [[NSBundle bundleForClass:[self class]] resourcePath];
	path = [path stringByAppendingPathComponent:@"BCRocks"];
	_rocks = [[RocksDB alloc] initWithPath:path andOptions:^(RocksDBOptions *options) {
		options.createIfMissing = YES;
	}];
}

- (void)tearDown
{
	[_rocks close];

	NSString * path = [[NSBundle bundleForClass:[self class]] resourcePath];
	path = [path stringByAppendingPathComponent:@"BCRocks"];

	NSError *error = nil;
	[[NSFileManager defaultManager] removeItemAtPath:path error:&error];
	if (error) {
		NSLog(@"Error test teardown: %@", [error debugDescription]);
	}
	[super tearDown];
}

- (void)testDB_Init
{
	NSString *key = @"key";
	NSString *value = @"value";

	BOOL ok = [_rocks setData:[value dataUsingEncoding:NSUTF8StringEncoding] forKey:[key dataUsingEncoding:NSUTF8StringEncoding]];
    XCTAssert(ok, @"Put Data");

	NSData *data = [_rocks dataForKey:[key dataUsingEncoding:NSUTF8StringEncoding]];
	XCTAssertNotNil(data);

	NSString *roundtrip = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	XCTAssertEqualObjects(roundtrip, value);
}

@end


//
//  FirebaseApp.m
//  ee_x
//
//  Created by Zinge on 5/10/17.
//
//

#include "ee/firebase/core/FirebaseApp.hpp"

#if defined(EE_X_IOS)
#import <UIKit/UIViewController.h>

#include <firebase/app.h>

#import <ee/core/internal/EEUtils.h>
#endif // EE_X_MOBILE

namespace ee {
namespace firebase {
using Self = App;

void Self::initialize() {
    static bool initialized = false;
    if (initialized) {
        return;
    }

#if defined(EE_X_IOS)
    auto options = ::firebase::AppOptions();
    auto app = ::firebase::App::Create(options);
    static_cast<void>(app);
#endif // EE_X_IOS

    initialized = true;
}

#if defined(EE_X_OSX)
WindowContext Self::getWindowContext() {
    return nil;
}
#elif defined(EE_X_IOS)
WindowContext Self::getWindowContext() {
    return [[EEUtils getCurrentRootViewController] view];
}
#endif // EE_X_OSX
} // namespace firebase
} // namespace ee

Fix to add [FIRApp configure].

//
//  FirebaseApp.m
//  ee_x
//
//  Created by Zinge on 5/10/17.
//
//

#include "ee/firebase/core/FirebaseApp.hpp"

#if defined(EE_X_IOS)
#import <FIRApp.h>
#import <UIKit/UIViewController.h>

#include <firebase/app.h>

#import <ee/core/internal/EEUtils.h>
#endif // EE_X_MOBILE

namespace ee {
namespace firebase {
using Self = App;

void Self::initialize() {
    static bool initialized = false;
    if (initialized) {
        return;
    }

#if defined(EE_X_IOS)
    [FIRApp configure];

    auto options = ::firebase::AppOptions();
    auto app = ::firebase::App::Create(options);
    static_cast<void>(app);
#endif // EE_X_IOS

    initialized = true;
}

#if defined(EE_X_OSX)
WindowContext Self::getWindowContext() {
    return nil;
}
#elif defined(EE_X_IOS)
WindowContext Self::getWindowContext() {
    return [[EEUtils getCurrentRootViewController] view];
}
#endif // EE_X_OSX
} // namespace firebase
} // namespace ee


Test case for r110250. Radar 8264670. Test case by Fariborz Jahanian!

// RUN: %llvmgcc %s -S -emit-llvm
struct TRunSoon {
  template <class P1> static void Post() {}
};

@implementation TPrivsTableViewMainController
- (void) applyToEnclosed {
  TRunSoon::Post<int>();
}
@end


/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#import "SkSampleNSView.h"
#include "SampleApp.h"
@implementation SkSampleNSView

- (id)initWithDefaults {
    if (self = [super initWithDefaults]) {
        fWind = new SampleWindow(self, NULL, NULL, NULL);
    }
    return self;
}

- (void)dealloc {
    delete fWind;
    [super dealloc];
}

- (void)swipeWithEvent:(NSEvent *)event {
    CGFloat x = [event deltaX];
    if (x < 0)
        ((SampleWindow*)fWind)->previousSample();
    else if (x > 0)
        ((SampleWindow*)fWind)->nextSample();
    else
        ((SampleWindow*)fWind)->showOverview();
}

@end

Fix cmdline argument passing in SampleApp/Mac.

/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#import "SkSampleNSView.h"
#include "SampleApp.h"
#include <crt_externs.h>
@implementation SkSampleNSView

- (id)initWithDefaults {
    if (self = [super initWithDefaults]) {
        fWind = new SampleWindow(self, *_NSGetArgc(), *_NSGetArgv(), NULL);
    }
    return self;
}

- (void)dealloc {
    delete fWind;
    [super dealloc];
}

- (void)swipeWithEvent:(NSEvent *)event {
    CGFloat x = [event deltaX];
    if (x < 0)
        ((SampleWindow*)fWind)->previousSample();
    else if (x > 0)
        ((SampleWindow*)fWind)->nextSample();
    else
        ((SampleWindow*)fWind)->showOverview();
}

@end


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "chrome/browser/cocoa/toolbar_view.h"

@implementation ToolbarView

@synthesize dividerOpacity = dividerOpacity_;

// Prevent mouse down events from moving the parent window around.
- (BOOL)mouseDownCanMoveWindow {
  return NO;
}

- (void)drawRect:(NSRect)rect {
  // The toolbar's background pattern is phased relative to the
  // tab strip view's background pattern.
  NSPoint phase = [self gtm_themePatternPhase];
  [[NSGraphicsContext currentContext] setPatternPhase:phase];
  [self drawBackground];
}

// Override of |-[BackgroundGradientView strokeColor]|; make it respect opacity.
- (NSColor*)strokeColor {
  return [[super strokeColor] colorWithAlphaComponent:[self dividerOpacity]];
}

@end

Make our toolbar tell accessibility it is a toolbar.

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "chrome/browser/cocoa/toolbar_view.h"

@implementation ToolbarView

@synthesize dividerOpacity = dividerOpacity_;

// Prevent mouse down events from moving the parent window around.
- (BOOL)mouseDownCanMoveWindow {
  return NO;
}

- (void)drawRect:(NSRect)rect {
  // The toolbar's background pattern is phased relative to the
  // tab strip view's background pattern.
  NSPoint phase = [self gtm_themePatternPhase];
  [[NSGraphicsContext currentContext] setPatternPhase:phase];
  [self drawBackground];
}

// Override of |-[BackgroundGradientView strokeColor]|; make it respect opacity.
- (NSColor*)strokeColor {
  return [[super strokeColor] colorWithAlphaComponent:[self dividerOpacity]];
}

- (BOOL)accessibilityIsIgnored {
  return NO;
}

- (id)accessibilityAttributeValue:(NSString*)attribute {
  if ([attribute isEqual:NSAccessibilityRoleAttribute])
    return NSAccessibilityToolbarRole;

  return [super accessibilityAttributeValue:attribute];
}

@end


Add a testcase that exercises DIBuilder's handling of cyclic debug info nodes.

// RUN: %clang_cc1 -triple x86_64-apple-darwin -g -emit-llvm %s -o - | FileCheck %s

// CHECK: ![[B:.*]] = {{.*}}, null, null, ![[BMEMBERS:.*]], null, null, null} ; [ DW_TAG_structure_type ] [B] [line [[@LINE+1]], size 8, align 8, offset 0] [def] [from ]
struct B {
  B(struct A *);
// CHECK: ![[BMEMBERS]] = !{![[BB:.*]]}
// CHECK: ![[BB]] = {{.*}} ![[B]], ![[TY:[0-9]+]], {{.*}}} ; [ DW_TAG_subprogram ] [line [[@LINE-2]]] [B]
// CHECK: ![[TY]] = {{.*}} ![[ARGS:[0-9]+]], null, null, null} ; [ DW_TAG_subroutine_type ]
// CHECK: ![[ARGS]] = !{null, ![[THIS:[0-9]+]],
// CHECK: ![[THIS]] = {{.*}}[[B]]} ; [ DW_TAG_pointer_type ] [
};

struct C {
 B b;
 C(struct A *);
 virtual ~C();
};

C::C(struct A *a)
  : b(a) {
}


// RUN: %clang_cc1 -triple x86_64-apple-macosx10.10 -std=c++11 -ast-dump %s | FileCheck %s
// CHECK: CXXCtorInitializer Field {{.*}} 'ptr' 'void *'

@interface NSObject
@end

@interface I : NSObject
@end

struct S {
  S();
  void *ptr = nullptr;
};

@implementation I
S::S() {}
@end

Add a test case to check a member's default constructor is also run.

// RUN: %clang_cc1 -triple x86_64-apple-macosx10.10 -std=c++11 -ast-dump %s | FileCheck %s
// CHECK: CXXCtorInitializer Field {{.*}} 'ptr' 'void *'
// CHECK: CXXCtorInitializer Field {{.*}} 'q' 'struct Q'

@interface NSObject
@end

@interface I : NSObject
@end

struct Q { Q(); };

struct S {
  S();
  void *ptr = nullptr;
  Q q;
};

@implementation I
S::S() {}
@end


// RUN: %clang_cc1 -fsyntax-only -verify %s
// rdar: // 8379892

struct X {
  X();
  X(const X&);
  ~X();

  static int staticData;
  int data;
  void method();
};

@interface A {
  X xval;
}

- (X)x;
- (void)setx:(X)x;
@end

void f(A* a) {
  a.x = X(); // expected-error {{setter method is needed to assign to object using property assignment syntax}}
}

struct Y : X { };

@interface B {
@private
  Y *y;
}
- (Y)value;
- (void)setValue : (Y) arg;
@property Y value;
@end

void g(B *b) {
  b.value.data = 17; // expected-error {{not assignable}}
  b.value.staticData = 17;
  b.value.method();
}

@interface C
@end

@implementation C
- (void)method:(B *)b {
  // <rdar://problem/8985943>
  b.operator+ = 17; // expected-error{{'operator+' is not a valid property name (accessing an object of type 'B *')}}
}
@end

Improve test case from prior commit ever so slightly

// RUN: %clang_cc1 -fsyntax-only -verify %s
// rdar: // 8379892

struct X {
  X();
  X(const X&);
  ~X();

  static int staticData;
  int data;
  void method();
};

@interface A {
  X xval;
}

- (X)x;
- (void)setx:(X)x;
@end

void f(A* a) {
  a.x = X(); // expected-error {{setter method is needed to assign to object using property assignment syntax}}
}

struct Y : X { };

@interface B {
@private
  Y *y;
}
- (Y)value;
- (void)setValue : (Y) arg;
@property Y value;
@end

void g(B *b) {
  b.value.data = 17; // expected-error {{not assignable}}
  b.value.staticData = 17;
  b.value.method();
}

@interface C
@end

@implementation C
- (void)method:(B *)b {
  // <rdar://problem/8985943>
  b.operator+ = 17; // expected-error{{'operator+' is not a valid property name (accessing an object of type 'B *')}}
  b->operator+ = 17; // expected-error{{'B' does not have a member named 'operator+'}}
}
@end


Test for previously checked in patch. // rdar://11374235

// RUN: %clang_cc1 -E %s -o %t.mm
// RUN: %clang_cc1 -x objective-c++ -fms-extensions -fobjc-default-synthesize-properties -rewrite-objc %t.mm -o %t-rw.cpp
// RUN: FileCheck --input-file=%t-rw.cpp %s
// RUN: %clang_cc1 -fsyntax-only  -Werror -DSEL="void *" -Did="struct objc_object *" -Wno-attributes -Wno-address-of-temporary -U__declspec -D"__declspec(X)=" %t-rw.cpp
// rdar://11374235

extern "C" void *sel_registerName(const char *);

@interface NSObject
- (void) release;
- (id) retain;
@end
@class NSString;

@interface SynthItAll : NSObject
@property int howMany;
@property (retain) NSString* what;
@end

@implementation SynthItAll
@end

@interface SynthSetter : NSObject
@property (nonatomic) int howMany;
@property (nonatomic, retain) NSString* what;
@end

@implementation SynthSetter

- (int) howMany {
    return _howMany;
}
// - (void) setHowMany: (int) value

- (NSString*) what {
    return _what;
}
// - (void) setWhat: (NSString*) value
@end

@interface SynthGetter : NSObject
@property (nonatomic) int howMany;
@property (nonatomic, retain) NSString* what;
@end

@implementation SynthGetter
// - (int) howMany
- (void) setHowMany: (int) value {
    _howMany = value;
}

// - (NSString*) what
- (void) setWhat: (NSString*) value {
    if (_what != value) {
        [_what release];
        _what = [value retain];
    }
}
@end

typedef struct {
        int x:1;
        int y:1;
} TBAR;

@interface NONAME
{
  TBAR _bar;
}
@property TBAR bad;
@end

@implementation NONAME
@end

// CHECK: (*(int *)((char *)self + OBJC_IVAR_$_SynthItAll$_howMany)) = howMany;
// CHECK: return (*(int *)((char *)self + OBJC_IVAR_$_SynthGetter$_howMany));
// CHECK: (*(TBAR *)((char *)self + OBJC_IVAR_$_NONAME$_bad)) = bad;


// RUN: %clang_cc1 -fsyntax-only -verify %s

// expected-no-diagnostics

struct S {};

@interface I
  @property (readonly) S* prop __attribute__((os_returns_retained));
  - (S*) generateS __attribute__((os_returns_retained));
  - (void) takeS:(S*) __attribute__((os_consumed)) s;
@end

Add more tests for os_returns_retained

// RUN: %clang_cc1 -fsyntax-only -verify -fblocks %s

struct S {};

@interface I
  @property (readonly) S* prop __attribute__((os_returns_retained));
  - (S*) generateS __attribute__((os_returns_retained));
  - (void) takeS:(S*) __attribute__((os_consumed)) s;
@end

typedef __attribute__((os_returns_retained)) id (^blockType)(); // expected-warning{{'os_returns_retained' attribute only applies to functions, Objective-C methods, and Objective-C properties}}

__auto_type b = ^ id (id filter)  __attribute__((os_returns_retained))  { // expected-warning{{'os_returns_retained' attribute only applies to functions, Objective-C methods, and Objective-C properties}}
  return filter;
};


//
//  CSystemUtilities.mm
//  SwingGame
//
//  Created by Tim Brier on 26/09/2014.
//  Copyright (c) 2014 tbrier. All rights reserved.
//

// =============================================================================
// Include Files
// -----------------------------------------------------------------------------
#include "CSystemUtilities.hpp"
#if SG_MAC
#import <Foundation/Foundation.h>
#endif

// =============================================================================
// CSystemUtilities::GetResourcePath
// Return the platform specific path to the resource location
// -----------------------------------------------------------------------------
std::string CSystemUtilities::GetResourcePath()
{
    std::string theReturnPath;

#if SG_MAC
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    NSBundle* bundle = [NSBundle mainBundle];

    if (bundle == nil)
    {
        DEBUG_LOG("Resource location can't be found: bundle is nil");
    }
    else
    {
        NSString* path = [bundle resourcePath];
        theReturnPath = [path UTF8String] + std::string("/");
    }

    [pool drain];
#endif

    return theReturnPath;
}

Add windows implementation of GetResourcePath

//
//  CSystemUtilities.mm
//  SwingGame
//
//  Created by Tim Brier on 26/09/2014.
//  Copyright (c) 2014 tbrier. All rights reserved.
//

// =============================================================================
// Include Files
// -----------------------------------------------------------------------------
#include "CSystemUtilities.hpp"

#if SG_MAC
#import <Foundation/Foundation.h>
#elif SG_WINDOWS
#include <windows.h>
#include <Shlwapi.h>
#endif

// =============================================================================
// CSystemUtilities::GetResourcePath
// Return the platform specific path to the resource location
// -----------------------------------------------------------------------------
std::string CSystemUtilities::GetResourcePath()
{
    std::string theReturnPath;

#if SG_MAC
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    NSBundle* bundle = [NSBundle mainBundle];

    if (bundle == nil)
    {
        DEBUG_LOG("Resource location can't be found: bundle is nil");
    }
    else
    {
        NSString* path = [bundle resourcePath];
        theReturnPath = [path UTF8String] + std::string("/");
    }

    [pool drain];
#elif SG_WINDOWS
	char buffer[MAX_PATH];
	DWORD result = GetModuleFileName(NULL, buffer, MAX_PATH);
	if (result == 0)
	{
		DEBUG_LOG("Failed to get module filename, error code %d", GetLastError());
	}
	else
	{
		PathRemoveFileSpec(buffer);
		theReturnPath = std::string(buffer) + std::string("\\");
	}
#endif

    return theReturnPath;
}


/*
 * WebViewWithKeyEquiv.mm
 *
 * Copyright (C) 2009-13 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#import "WebViewWithKeyEquiv.h"

@implementation WebViewWithKeyEquiv

- (void) setKeyEquivDelegate: (id) delegate
{
   keyEquivDelegate_ = delegate;
}

- (BOOL) performKeyEquivalent: (NSEvent *) theEvent
{
   if (keyEquivDelegate_ != nil)
   {
      return [keyEquivDelegate_ performKeyEquivalent: theEvent];
   }
   return [super performKeyEquivalent: theEvent];
}

@end

Revert "fix window cycling between plots and main window via shortcut key"

/*
 * WebViewWithKeyEquiv.mm
 *
 * Copyright (C) 2009-13 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#import "WebViewWithKeyEquiv.h"

@implementation WebViewWithKeyEquiv

- (void) setKeyEquivDelegate: (id) delegate
{
   keyEquivDelegate_ = delegate;
}

- (BOOL) performKeyEquivalent: (NSEvent *) theEvent
{
   if (keyEquivDelegate_ != nil && [keyEquivDelegate_ performKeyEquivalent: theEvent])
      return YES;
   return [super performKeyEquivalent: theEvent];
}

@end


/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */

#include <kroll/kroll.h>
#include "../app_binding.h"
#include <Foundation/Foundation.h>

namespace ti
{

void AppBinding::Restart(const ValueList& args, KValueRef result)
{
	Host* host = Host::GetInstance();
	std::string cmdline(host->GetApplication->arguments.at(0));

	NSProcessInfo* p = [NSProcessInfo processInfo];
	NSString* path = [[NSBundle mainBundle] bundlePath];
	NSString* killArg1AndOpenArg2Script = [NSString
		stringWithFormat:@"kill -9 %d\n open \"%@\"",
		[p processIdentifier], path];

	// -c tells sh to execute the next argument, passing it the remaining arguments.
	NSArray* shArgs = [NSArray arrayWithObjects:@"-c",
		killArg1AndOpenArg2Script, nil];
	NSTask* restartTask = [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:shArgs];
	[restartTask waitUntilExit]; //wait for killArg1AndOpenArg2Script to finish
}

}

Build fix for OS X.

/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */

#include <kroll/kroll.h>
#include "../app_binding.h"
#include <Foundation/Foundation.h>

namespace ti
{

void AppBinding::Restart(const ValueList& args, KValueRef result)
{
	Host* host = Host::GetInstance();
	std::string cmdline(host->GetApplication()->arguments.at(0));

	NSProcessInfo* p = [NSProcessInfo processInfo];
	NSString* path = [[NSBundle mainBundle] bundlePath];
	NSString* killArg1AndOpenArg2Script = [NSString
		stringWithFormat:@"kill -9 %d\n open \"%@\"",
		[p processIdentifier], path];

	// -c tells sh to execute the next argument, passing it the remaining arguments.
	NSArray* shArgs = [NSArray arrayWithObjects:@"-c",
		killArg1AndOpenArg2Script, nil];
	NSTask* restartTask = [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:shArgs];
	[restartTask waitUntilExit]; //wait for killArg1AndOpenArg2Script to finish
}

}


// RUN: %clang_cc1 -x objective-c++ -fblocks -fms-extensions -rewrite-objc %s -o %t-rw.cpp
// RUN: FileCheck -check-prefix LP --input-file=%t-rw.cpp %s
// radar 7589414

@protocol NSPortDelegate;
@interface NSConnection @end

@interface NSMessagePort
- (void) clone;
@end

@implementation NSMessagePort
- (void) clone {
     NSConnection <NSPortDelegate> *conn = 0;
     id <NSPortDelegate> *idc = 0;
}
@end

// radar 7607413
@protocol Proto1, Proto2;

@protocol Proto
@end

unsigned char func(id<Proto1, Proto2> inProxy);

id bar(id);

void f() {
        id a;
        id b = bar((id <Proto>)a);
}

// CHECK-LP: NSConnection /*<NSPortDelegate>*/ *conn = 0;

// CHECK-LP: id /*<NSPortDelegate>*/ *idc = 0;

// CHECK-LP: func(id/*<Proto1, Proto2>*/ inProxy);

// CHECK-LP: bar((id /*<Proto>*/)a);

Make rewritten source compiled with clang++.

// RUN: %clang_cc1 -x objective-c++ -Wno-return-type -fblocks -fms-extensions -rewrite-objc %s -o %t-rw.cpp
// RUN: %clang_cc1 -fsyntax-only -Wno-address-of-temporary -D"SEL=void*" -D"id=void*" -D"__declspec(X)=" %t-rw.cpp
// radar 7589414

@protocol NSPortDelegate;
@interface NSConnection @end

@interface NSMessagePort
- (void) clone;
@end

@implementation NSMessagePort
- (void) clone {
     NSConnection <NSPortDelegate> *conn = 0;
     id <NSPortDelegate> *idc = 0;
}
@end

// radar 7607413
@protocol Proto1, Proto2;

@protocol Proto
@end

unsigned char func(id<Proto1, Proto2> inProxy);

id bar(id);

void f() {
        id a;
        id b = bar((id <Proto>)a);
}


//
//  CDAMarkdownViewController.m
//  ContentfulSDK
//
//  Created by Boris Bügling on 17/03/14.
//
//

#import <Bypass/Bypass.h>

#import "CDAMarkdownViewController.h"

@interface CDAMarkdownViewController ()

@property (nonatomic) UITextView* textView;

@end

#pragma mark -

@implementation CDAMarkdownViewController

-(void)setMarkdownText:(NSString *)markdownText {
    _markdownText = markdownText;

    BPDocument* document = [[BPParser new] parse:markdownText];
    NSAttributedString* attributedText = [[BPAttributedStringConverter new] convertDocument:document];

    self.textView.attributedText = attributedText;
}

-(void)viewDidLoad {
    [super viewDidLoad];

    self.textView = [[UITextView alloc] initWithFrame:self.view.bounds];
    self.textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.textView.editable = NO;
    self.textView.font = [UIFont systemFontOfSize:18.0];
    self.textView.textContainerInset = UIEdgeInsetsMake(20.0, 10.0, 10.0, 20.0);
    [self.view addSubview:self.textView];

    [self setMarkdownText:self.markdownText];
}

@end

Increase font-size for block quotes.

//
//  CDAMarkdownViewController.m
//  ContentfulSDK
//
//  Created by Boris Bügling on 17/03/14.
//
//

#import <Bypass/Bypass.h>

#import "CDAMarkdownViewController.h"

@interface CDAMarkdownViewController ()

@property (nonatomic) UITextView* textView;

@end

#pragma mark -

@implementation CDAMarkdownViewController

-(void)setMarkdownText:(NSString *)markdownText {
    _markdownText = markdownText;

    BPDocument* document = [[BPParser new] parse:markdownText];
    BPAttributedStringConverter* converter = [BPAttributedStringConverter new];
    converter.displaySettings.quoteFont = [UIFont fontWithName:@"Marion-Italic"
                                                          size:[UIFont systemFontSize] + 1.0f];
    NSAttributedString* attributedText = [converter convertDocument:document];

    self.textView.attributedText = attributedText;
}

-(void)viewDidLoad {
    [super viewDidLoad];

    self.textView = [[UITextView alloc] initWithFrame:self.view.bounds];
    self.textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.textView.editable = NO;
    self.textView.font = [UIFont systemFontOfSize:18.0];
    self.textView.textContainerInset = UIEdgeInsetsMake(20.0, 10.0, 10.0, 20.0);
    [self.view addSubview:self.textView];

    [self setMarkdownText:self.markdownText];
}

@end


// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/common_web_contents_delegate.h"

#import <Cocoa/Cocoa.h>

#include "brightray/browser/mac/event_dispatching_window.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "ui/events/keycodes/keyboard_codes.h"

namespace atom {

void CommonWebContentsDelegate::HandleKeyboardEvent(
    content::WebContents* source,
    const content::NativeWebKeyboardEvent& event) {
  if (event.skip_in_browser ||
      event.type == content::NativeWebKeyboardEvent::Char)
    return;

  // Escape exits tabbed fullscreen mode.
  if (event.windowsKeyCode == ui::VKEY_ESCAPE && is_html_fullscreen())
    ExitFullscreenModeForTab(source);

  if (event.os_event.window)
    [(EventDispatchingWindow*)event.os_event.window redispatchKeyEvent:event.os_event];
}

}  // namespace atom

Use class extension to avoid type conversion

// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/common_web_contents_delegate.h"

#import <Cocoa/Cocoa.h>

#include "brightray/browser/mac/event_dispatching_window.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "ui/events/keycodes/keyboard_codes.h"

@interface NSWindow (EventDispatchingWindow)
- (void)redispatchKeyEvent:(NSEvent*)event;
@end

namespace atom {

void CommonWebContentsDelegate::HandleKeyboardEvent(
    content::WebContents* source,
    const content::NativeWebKeyboardEvent& event) {
  if (event.skip_in_browser ||
      event.type == content::NativeWebKeyboardEvent::Char)
    return;

  // Escape exits tabbed fullscreen mode.
  if (event.windowsKeyCode == ui::VKEY_ESCAPE && is_html_fullscreen())
    ExitFullscreenModeForTab(source);

  if (event.os_event.window)
    [event.os_event.window redispatchKeyEvent:event.os_event];
}

}  // namespace atom


// RUN: %clang_cc1 -fobjc-arc -fobjc-runtime-has-weak -fblocks -triple x86_64-apple-darwin10.0.0 -emit-llvm -o - %s | FileCheck %s

// CHECK-LABEL: define void @_Z28test_objc_object_pseudo_dtorPU8__strongP11objc_objectPU6__weakS0_
void test_objc_object_pseudo_dtor(__strong id *ptr, __weak id *wptr) {
  // CHECK: load i8***
  // CHECK-NEXT: load i8**
  // CHECK-NEXT: call void @objc_release
  ptr->~id();

  // CHECK: call void @objc_destroyWeak(i8** {{%.*}})
  wptr->~id();

  // CHECK: load i8***
  // CHECK-NEXT: load i8**
  // CHECK-NEXT: call void @objc_release
  (*ptr).~id();

  // CHECK: call void @objc_destroyWeak(i8** {{%.*}})
  (*wptr).~id();
  // CHECK: ret void
}

Remove trailing whitespace to make test compatible with typeless pointer migration


#include "OSXUtils.hpp"

#include "common/debug.h"

#import <Cocoa/Cocoa.h>

namespace sw
{
namespace OSX
{
	bool IsValidWindow(EGLNativeWindowType window)
	{
		NSObject *object = reinterpret_cast<NSObject*>(window);
		return window && ([object isKindOfClass:[NSView class]] || [object isKindOfClass:[CALayer class]]);
	}

	void GetNativeWindowSize(EGLNativeWindowType window, int &width, int &height)
	{
		NSObject *object = reinterpret_cast<NSObject*>(window);

		if([object isKindOfClass:[NSView class]])
		{
			NSView *view = reinterpret_cast<NSView*>(object);
			width = [view bounds].size.width;
			height = [view bounds].size.height;
		}
		else if([object isKindOfClass:[CALayer class]])
		{
			CALayer *layer = reinterpret_cast<CALayer*>(object);
			width = CGRectGetWidth([layer frame]);
			height = CGRectGetHeight([layer frame]);
		}
		else UNREACHABLE(0);
	}
}
}

Fix OSX retina display support.

#include "OSXUtils.hpp"

#include "common/debug.h"

#import <Cocoa/Cocoa.h>

namespace sw
{
namespace OSX
{
	bool IsValidWindow(EGLNativeWindowType window)
	{
		NSObject *object = reinterpret_cast<NSObject*>(window);
		return window && ([object isKindOfClass:[NSView class]] || [object isKindOfClass:[CALayer class]]);
	}

	void GetNativeWindowSize(EGLNativeWindowType window, int &width, int &height)
	{
		NSObject *object = reinterpret_cast<NSObject*>(window);

		if([object isKindOfClass:[NSView class]])
		{
			NSView *view = reinterpret_cast<NSView*>(object);
			width = [view convertRectToBacking:[view bounds]].size.width;
			height = [view convertRectToBacking:[view bounds]].size.height;
		}
		else if([object isKindOfClass:[CALayer class]])
		{
			CALayer *layer = reinterpret_cast<CALayer*>(object);
			width = [layer bounds].size.width * layer.contentsScale;
			height = [layer bounds].size.height * layer.contentsScale;
		}
		else UNREACHABLE(0);
	}
}
}


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import <Cocoa/Cocoa.h>

#include "base/scoped_nsobject.h"
#import "chrome/browser/cocoa/task_manager_mac.h"
#import "chrome/browser/cocoa/cocoa_test_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"

namespace {

class TaskManagerWindowControllerTest : public PlatformTest {
 public:
  TaskManagerWindowControllerTest() {
    controller_.reset([[TaskManagerWindowController alloc] init]);
  }

  scoped_nsobject<TaskManagerWindowController> controller_;
  CocoaTestHelper cocoa_helper_;  // Inits Cocoa, creates window, etc...
};

// Test creation, to ensure nothing leaks or crashes
TEST_F(TaskManagerWindowControllerTest, Init) {
}

// TODO(thakis): Add tests for more methods as they become implemented
// (TaskManager::Show() etc).

}  // namespace

Move TaskManagerMacUnitTest over to Cocoatest.

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import <Cocoa/Cocoa.h>

#include "base/scoped_nsobject.h"
#import "chrome/browser/cocoa/task_manager_mac.h"
#import "chrome/browser/cocoa/cocoa_test_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"

namespace {

class TaskManagerWindowControllerTest : public CocoaTest {
 public:
  virtual void SetUp() {
    CocoaTest::SetUp();
    controller_ = [[TaskManagerWindowController alloc] init];
  }

  virtual void TearDown() {
    [controller_ close];
    CocoaTest::TearDown();
  }

  TaskManagerWindowController *controller_;
};

// Test creation, to ensure nothing leaks or crashes
TEST_F(TaskManagerWindowControllerTest, Init) {
}

// TODO(thakis): Add tests for more methods as they become implemented
// (TaskManager::Show() etc).

}  // namespace


/*
 * Copyright 2021 Google LLC
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "experimental/graphite/src/mtl/MtlCommandBuffer.h"

namespace skgpu::mtl {

std::unique_ptr<CommandBuffer> CommandBuffer::Make(id<MTLCommandQueue> queue) {
    sk_cfp<MTLCommandBufferDescriptor*> desc([[MTLCommandBufferDescriptor alloc] init]);
    (*desc).retainedReferences = NO;
#ifdef SK_ENABLE_MTL_DEBUG_INFO
    (*desc).errorOptions = MTLCommandBufferErrorOptionEncoderExecutionStatus;
#endif

    // We add a retain here because the command buffer is set to autorelease (not alloc or copy)
    sk_cfp<id<MTLCommandBuffer>> cmdBuffer([[queue commandBufferWithDescriptor:desc.get()] retain]);
    if (cmdBuffer == nil) {
        return nullptr;
    }

#ifdef SK_ENABLE_MTL_DEBUG_INFO
     (*cmdBuffer).label = @"CommandBuffer::Make";
#endif

    return std::unique_ptr<CommandBuffer>(new CommandBuffer(std::move(cmdBuffer)));
}

} // namespace skgpu::mtl

Fix creation of command buffer for different SDK/OS versions

/*
 * Copyright 2021 Google LLC
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "experimental/graphite/src/mtl/MtlCommandBuffer.h"

namespace skgpu::mtl {

std::unique_ptr<CommandBuffer> CommandBuffer::Make(id<MTLCommandQueue> queue) {
    sk_cfp<id<MTLCommandBuffer>> cmdBuffer;
#if GR_METAL_SDK_VERSION >= 230
    if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) {
        sk_cfp<MTLCommandBufferDescriptor*> desc([[MTLCommandBufferDescriptor alloc] init]);
        (*desc).retainedReferences = NO;
#ifdef SK_ENABLE_MTL_DEBUG_INFO
        (*desc).errorOptions = MTLCommandBufferErrorOptionEncoderExecutionStatus;
#endif
        // We add a retain here because the command buffer is set to autorelease (not alloc or copy)
        cmdBuffer.reset([[queue commandBufferWithDescriptor:desc.get()] retain]);
    } else {
#endif
        // We add a retain here because the command buffer is set to autorelease (not alloc or copy)
        cmdBuffer.reset([[queue commandBufferWithUnretainedReferences] retain]);
#if GR_METAL_SDK_VERSION >= 230
    }
#endif
    if (cmdBuffer == nil) {
        return nullptr;
    }

#ifdef SK_ENABLE_MTL_DEBUG_INFO
     (*cmdBuffer).label = @"CommandBuffer::Make";
#endif

    return std::unique_ptr<CommandBuffer>(new CommandBuffer(std::move(cmdBuffer)));
}

} // namespace skgpu::mtl


// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -g -emit-obj %s

// This test passes if clang doesn't crash.

template <class C> class scoped_ptr {
public:
  C* operator->() const { return 0; }
};

@class NSWindow;
@class NSImage;
@interface NSWindow {
  NSImage *_miniIcon;
}
-(id)windowController;
@end

class AutomationResourceTracker {
public:
  NSWindow* GetResource(int handle) { return 0; }
};

# 13 "automation/automation_window_tracker.h"
class AutomationWindowTracker : public AutomationResourceTracker { };

template<typename NST> class scoped_nsobject { };

@interface TabStripController{
  scoped_nsobject<NSImage> defaultFavicon_;
}
@end

@interface BrowserWindowController {
  TabStripController* tabStripController_;
}
@end

void WindowGetViewBounds(scoped_ptr<AutomationWindowTracker> window_tracker_) {
  NSWindow* window = window_tracker_->GetResource(42);
  BrowserWindowController* controller = [window windowController];
}


#include <boxer/boxer.h>
#import <Cocoa/Cocoa.h>

namespace boxer {

void show(const char *message, const char *title) {
   NSAlert *alert = [[NSAlert alloc] init];
   [alert addButtonWithTitle:@"OK"];
   [alert setMessageText:[NSString stringWithCString:title
                                   encoding:[NSString defaultCStringEncoding]]];
   [alert setInformativeText:[NSString stringWithCString:message
                                       encoding:[NSString defaultCStringEncoding]]];
   [alert setAlertStyle:NSWarningAlertStyle];

   [alert runModal];
   [alert release];
}

} // namespace boxer

Implement OS X expanded show

#include <boxer/boxer.h>
#import <Cocoa/Cocoa.h>

namespace boxer {

namespace {

NSString* const OK_STR = @"OK";
NSString* const CANCEL_STR = @"Cancel";
NSString* const YES_STR = @"Yes";
NSString* const NO_STR = @"No";

NSAlertStyle getAlertStyle(Style style) {
   switch (style) {
      case Style::Info:
         return NSInformationalAlertStyle;
      case Style::Warning:
         return NSWarningAlertStyle;
      case Style::Error:
         return NSCriticalAlertStyle;
      case Style::Question:
         return NSWarningAlertStyle;
      default:
         return NSInformationalAlertStyle;
   }
}

void setButtons(NSAlert *alert, Buttons buttons) {
   switch (buttons) {
      case Buttons::OK:
         [alert addButtonWithTitle:OK_STR];
         break;
      case Buttons::OKCancel:
         [alert addButtonWithTitle:OK_STR];
         [alert addButtonWithTitle:CANCEL_STR];
         break;
      case Buttons::YesNo:
         [alert addButtonWithTitle:YES_STR];
         [alert addButtonWithTitle:NO_STR];
         break;
      default:
         [alert addButtonWithTitle:OK_STR];
   }
}

Selection getSelection(int index, Buttons buttons) {
   switch (buttons) {
      case Buttons::OK:
         return index == NSAlertFirstButtonReturn ? Selection::OK : Selection::None;
      case Buttons::OKCancel:
         if (index == NSAlertFirstButtonReturn) {
            return Selection::OK;
         } else if (index == NSAlertSecondButtonReturn) {
            return Selection::Cancel;
         } else {
            return Selection::None;
         }
      case Buttons::YesNo:
         if (index == NSAlertFirstButtonReturn) {
            return Selection::Yes;
         } else if (index == NSAlertSecondButtonReturn) {
            return Selection::No;
         } else {
            return Selection::None;
         }
      default:
         return Selection::None;
   }
}

} // namespace

Selection show(const char *message, const char *title, Style style, Buttons buttons) {
   NSAlert *alert = [[NSAlert alloc] init];

   [alert setMessageText:[NSString stringWithCString:title
                                   encoding:[NSString defaultCStringEncoding]]];
   [alert setInformativeText:[NSString stringWithCString:message
                                       encoding:[NSString defaultCStringEncoding]]];

   [alert setAlertStyle:getAlertStyle(style)];
   setButtons(alert, buttons);

   Selection selection = getSelection([alert runModal], buttons);
   [alert release];

   return selection;
}

} // namespace boxer


//
//  IOSInputModule.mm
//  GameEngine
//
//  Created by Jon Sharkey on 2013-11-13.
//  Copyright 2013 Sharkable. All rights reserved.
//

#include "gameengine/apple/modules/ios/IOSInputModule.h"

IOSInputModule::IOSInputModule()
    : device_angle_(0){
  motion_manager_ = [[CMMotionManager alloc] init];
  motion_manager_.accelerometerUpdateInterval = 1.0 / 60.0;
  operation_queue_ = [[NSOperationQueue alloc] init];
}

IOSInputModule::~IOSInputModule() {
  [motion_manager_ release];
  [operation_queue_ release];
}

void IOSInputModule::TurnOnRotationUpdates() {
  [motion_manager_ startDeviceMotionUpdatesToQueue:operation_queue_
      withHandler:^(CMDeviceMotion *motion, NSError *error) {
          device_angle_ = -atan2f(motion.gravity.y, motion.gravity.x) * 180.f / M_PI;
      }
  ];
}

void IOSInputModule::TurnOffRotationUpdates() {
  [motion_manager_ stopDeviceMotionUpdates];
}

Update device motion less often.

//
//  IOSInputModule.mm
//  GameEngine
//
//  Created by Jon Sharkey on 2013-11-13.
//  Copyright 2013 Sharkable. All rights reserved.
//

#include "gameengine/apple/modules/ios/IOSInputModule.h"

IOSInputModule::IOSInputModule()
    : device_angle_(0){
  motion_manager_ = [[CMMotionManager alloc] init];
  motion_manager_.accelerometerUpdateInterval = 1.0 / 5.0;
  operation_queue_ = [[NSOperationQueue alloc] init];
}

IOSInputModule::~IOSInputModule() {
  [motion_manager_ release];
  [operation_queue_ release];
}

void IOSInputModule::TurnOnRotationUpdates() {
  [motion_manager_ startDeviceMotionUpdatesToQueue:operation_queue_
      withHandler:^(CMDeviceMotion *motion, NSError *error) {
          device_angle_ = -atan2f(motion.gravity.y, motion.gravity.x) * 180.f / M_PI;
      }
  ];
}

void IOSInputModule::TurnOffRotationUpdates() {
  [motion_manager_ stopDeviceMotionUpdates];
}


// Copyright 2015-2020 Elviss Strazdins. All rights reserved.

#include "AutoreleasePool.hpp"

namespace ouzel::core::cocoa
{
    AutoreleasePool::AutoreleasePool() noexcept:
        pool([[NSAutoreleasePool alloc] init])
    {
    }

    AutoreleasePool::~AutoreleasePool()
    {
        [pool release];
    }

    AutoreleasePool::AutoreleasePool(const AutoreleasePool& other) noexcept:
        pool([other.pool retain])
    {
    }

    AutoreleasePool::AutoreleasePool(AutoreleasePool&& other) noexcept:
        pool(other.pool)
    {
        other.pool = nil;
    }

    AutoreleasePool& AutoreleasePool::operator=(const AutoreleasePool& other) noexcept
    {
        [pool release];
        pool = [other.pool retain];
        return *this;
    }

    AutoreleasePool& AutoreleasePool::operator=(AutoreleasePool&& other) noexcept
    {
        pool = other.pool;
        other.pool = nil;
        return *this;
    }

    bool AutoreleasePool::operator==(const AutoreleasePool& other) const noexcept
    {
        return pool == other.pool;
    }

    bool AutoreleasePool::operator!=(const AutoreleasePool& other) const noexcept
    {
        return pool != other.pool;
    }
}

Check if not assigning to self

// Copyright 2015-2020 Elviss Strazdins. All rights reserved.

#include "AutoreleasePool.hpp"

namespace ouzel::core::cocoa
{
    AutoreleasePool::AutoreleasePool() noexcept:
        pool([[NSAutoreleasePool alloc] init])
    {
    }

    AutoreleasePool::~AutoreleasePool()
    {
        [pool release];
    }

    AutoreleasePool::AutoreleasePool(const AutoreleasePool& other) noexcept:
        pool([other.pool retain])
    {
    }

    AutoreleasePool::AutoreleasePool(AutoreleasePool&& other) noexcept:
        pool(other.pool)
    {
        other.pool = nil;
    }

    AutoreleasePool& AutoreleasePool::operator=(const AutoreleasePool& other) noexcept
    {
        if (this == &other) return *this;
        [pool release];
        pool = [other.pool retain];
        return *this;
    }

    AutoreleasePool& AutoreleasePool::operator=(AutoreleasePool&& other) noexcept
    {
        if (this == &other) return *this;
        pool = other.pool;
        other.pool = nil;
        return *this;
    }

    bool AutoreleasePool::operator==(const AutoreleasePool& other) const noexcept
    {
        return pool == other.pool;
    }

    bool AutoreleasePool::operator!=(const AutoreleasePool& other) const noexcept
    {
        return pool != other.pool;
    }
}


/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#import <Cocoa/Cocoa.h>

// FIXME: should be in a header
void setSystemPreferences();

void setSystemPreferences() {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Set LCD font smoothing level for this application (does not affect other
    // applications). Based on resetDefaultsToConsistentValues() in
    // http://trac.webkit.org/browser/trunk/Tools/DumpRenderTree/mac/DumpRenderTree.mm
    enum {
        NoFontSmoothing     = 0,
        LightFontSmoothing  = 1,
        MediumFontSmoothing = 2,
        StrongFontSmoothing = 3,
    };
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:MediumFontSmoothing forKey:@"AppleFontSmoothing"];

    [pool release];
}

Include system_preferences.h in mac file.

/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "system_preferences.h"

#import <Cocoa/Cocoa.h>

void setSystemPreferences() {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Set LCD font smoothing level for this application (does not affect other
    // applications). Based on resetDefaultsToConsistentValues() in
    // http://trac.webkit.org/browser/trunk/Tools/DumpRenderTree/mac/DumpRenderTree.mm
    enum {
        NoFontSmoothing     = 0,
        LightFontSmoothing  = 1,
        MediumFontSmoothing = 2,
        StrongFontSmoothing = 3,
    };
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:MediumFontSmoothing forKey:@"AppleFontSmoothing"];

    [pool release];
}


// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/app/atom_main_delegate.h"

#include "base/mac/bundle_locations.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "brightray/common/mac/main_application_bundle.h"
#include "content/public/common/content_paths.h"

namespace atom {

namespace {

base::FilePath GetFrameworksPath() {
  return brightray::MainApplicationBundlePath().Append("Contents")
                                               .Append("Frameworks");
}

}  // namespace

void AtomMainDelegate::OverrideFrameworkBundlePath() {
  base::mac::SetOverrideFrameworkBundlePath(
      GetFrameworksPath().Append("Atom Framework.framework"));
}

void AtomMainDelegate::OverrideChildProcessPath() {
  base::FilePath helper_path = GetFrameworksPath().Append("Atom Helper.app")
                                                  .Append("Contents")
                                                  .Append("MacOS")
                                                  .Append("Atom Helper");
  PathService::Override(content::CHILD_PROCESS_EXE, helper_path);
}

}  // namespace atom

Determine the Helper name from the App name

// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/app/atom_main_delegate.h"

#include "base/mac/bundle_locations.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "brightray/common/mac/main_application_bundle.h"
#include "content/public/common/content_paths.h"

namespace atom {

namespace {

base::FilePath GetFrameworksPath() {
  return brightray::MainApplicationBundlePath().Append("Contents")
                                               .Append("Frameworks");
}

std::string GetApplicationName() {
  std::string name = brightray::MainApplicationBundlePath().BaseName().AsUTF8Unsafe();
  return name.substr(0, name.length() - 4/*.app*/);
}

}  // namespace

void AtomMainDelegate::OverrideFrameworkBundlePath() {
  base::FilePath bundlePath = GetFrameworksPath();
  std::string app_name = GetApplicationName();

  base::mac::SetOverrideFrameworkBundlePath(bundlePath
      .Append(app_name + " Framework.framework"));
}

void AtomMainDelegate::OverrideChildProcessPath() {
  std::string app_name = GetApplicationName();

  base::FilePath helper_path = GetFrameworksPath().Append(app_name + " Helper.app")
                                                  .Append("Contents")
                                                  .Append("MacOS")
                                                  .Append(app_name + " Helper");
  PathService::Override(content::CHILD_PROCESS_EXE, helper_path);
}

}  // namespace atom


#ifdef PIXELBOOST_PLATFORM_OSX

#include "pixelboost/file/fileHelpers.h"

namespace pb
{

namespace FileHelpers
{

std::string GetRootPath()
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    std::string rootPath = [[[NSBundle mainBundle] resourcePath] UTF8String];
    [pool release];
    return rootPath;
}

}

}

#endif

Add mac implementation of file helper functions

#ifdef PIXELBOOST_PLATFORM_OSX

#include "pixelboost/file/fileHelpers.h"

namespace pb
{

namespace FileHelpers
{

std::string GetRootPath()
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    std::string rootPath = [[[NSBundle mainBundle] resourcePath] UTF8String];
    [pool release];
    return rootPath;
}

std::string GetUserPath()
{
    return "/";
}

bool pb::FileHelpers::CreateDirectory(const std::string& directory)
{
    NSString* dirToCreate = [NSString stringWithUTF8String:directory.c_str()];
    NSError* error = nil;
    BOOL isDir=YES;

    if([[NSFileManager defaultManager] fileExistsAtPath:dirToCreate isDirectory:&isDir] || !isDir)
        return false;

    if(![[NSFileManager defaultManager] createDirectoryAtPath:dirToCreate withIntermediateDirectories:YES attributes:nil error:&error])
    {
        return false;
    }

    return true;
}

int pb::FileHelpers::GetTimestamp(const std::string& filename)
{
    NSDictionary* attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithUTF8String:filename.c_str()] error:nil];

    if (attrs != nil)
    {
        NSDate *date = (NSDate*)[attrs objectForKey: NSFileModificationDate];
        return (int)[date timeIntervalSince1970];
    }
    else {
        return 0;
    }
}

}

}

#endif


//
//  NSArray+MCO.cpp
//  mailcore2
//
//  Created by DINH Viêt Hoà on 1/29/13.
//  Copyright (c) 2013 MailCore. All rights reserved.
//

#import "NSArray+MCO.h"

#include "MCBaseTypes.h"

#import "NSObject+MCO.h"

@implementation NSArray (MCO)

+ (id) mco_objectWithMCObject:(mailcore::Object *)object
{
    return [self mco_arrayWithMCArray:(mailcore::Array *) object];
}

+ (NSArray *) mco_arrayWithMCArray:(mailcore::Array *)array
{
    NSMutableArray * result = [NSMutableArray array];
    for(unsigned int i = 0 ; i < array->count() ; i ++) {
        [result addObject:[NSObject mco_objectWithMCObject:array->objectAtIndex(i)]];
    }
    return result;
}

- (mailcore::Array *) mco_mcArray
{
    mailcore::Array * result = mailcore::Array::array();
    for(NSObject * value in self) {
        [value mco_mcObject];
    }
    return result;
}

@end

Fix copying of array contents

//
//  NSArray+MCO.cpp
//  mailcore2
//
//  Created by DINH Viêt Hoà on 1/29/13.
//  Copyright (c) 2013 MailCore. All rights reserved.
//

#import "NSArray+MCO.h"

#include "MCBaseTypes.h"

#import "NSObject+MCO.h"

@implementation NSArray (MCO)

+ (id) mco_objectWithMCObject:(mailcore::Object *)object
{
    return [self mco_arrayWithMCArray:(mailcore::Array *) object];
}

+ (NSArray *) mco_arrayWithMCArray:(mailcore::Array *)array
{
    NSMutableArray * result = [NSMutableArray array];
    for(unsigned int i = 0 ; i < array->count() ; i ++) {
        [result addObject:[NSObject mco_objectWithMCObject:array->objectAtIndex(i)]];
    }
    return result;
}

- (mailcore::Array *) mco_mcArray
{
    mailcore::Array * result = mailcore::Array::array();
    for(NSObject * value in self) {
		result->addObject([value mco_mcObject]);
    }
    return result;
}

@end


// RUN: %clang_tsan %s -o %t -framework Foundation
// RUN: %run %t 2>&1

#import <Foundation/Foundation.h>

void notify_callback(void *context) {
  // Do nothing.
}

int main() {
  NSLog(@"Hello world.");

  dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

  for (int i = 0; i < 300000; i++) {
    dispatch_group_t g = dispatch_group_create();
    dispatch_group_enter(g);
    dispatch_async(q, ^{
      dispatch_group_leave(g);
    });
    dispatch_group_notify(g, q, ^{
      // Do nothing.
    });
    dispatch_release(g);
  }

  for (int i = 0; i < 300000; i++) {
    dispatch_group_t g = dispatch_group_create();
    dispatch_group_enter(g);
    dispatch_async(q, ^{
      dispatch_group_leave(g);
    });
    dispatch_group_notify_f(g, q, nullptr, &notify_callback);
    dispatch_release(g);
  }

  NSLog(@"Done.");
}

// CHECK: Hello world.
// CHECK: Done.
// CHECK-NOT: WARNING: ThreadSanitizer
// CHECK-NOT: CHECK failed

Change nullptr to NULL in one Darwin test.

// RUN: %clang_tsan %s -o %t -framework Foundation
// RUN: %run %t 2>&1

#import <Foundation/Foundation.h>

void notify_callback(void *context) {
  // Do nothing.
}

int main() {
  NSLog(@"Hello world.");

  dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

  for (int i = 0; i < 300000; i++) {
    dispatch_group_t g = dispatch_group_create();
    dispatch_group_enter(g);
    dispatch_async(q, ^{
      dispatch_group_leave(g);
    });
    dispatch_group_notify(g, q, ^{
      // Do nothing.
    });
    dispatch_release(g);
  }

  for (int i = 0; i < 300000; i++) {
    dispatch_group_t g = dispatch_group_create();
    dispatch_group_enter(g);
    dispatch_async(q, ^{
      dispatch_group_leave(g);
    });
    dispatch_group_notify_f(g, q, NULL, &notify_callback);
    dispatch_release(g);
  }

  NSLog(@"Done.");
}

// CHECK: Hello world.
// CHECK: Done.
// CHECK-NOT: WARNING: ThreadSanitizer
// CHECK-NOT: CHECK failed


// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/ui/accelerator_util.h"

#include "ui/base/accelerators/accelerator.h"
#import "ui/base/accelerators/platform_accelerator_cocoa.h"
#import "ui/events/keycodes/keyboard_code_conversion_mac.h"

namespace accelerator_util {

void SetPlatformAccelerator(ui::Accelerator* accelerator) {
  unichar character;
  unichar characterIgnoringModifiers;
  ui::MacKeyCodeForWindowsKeyCode(accelerator->key_code(),
                                  0,
                                  &character,
                                  &characterIgnoringModifiers);
  NSString* characters =
      [[[NSString alloc] initWithCharacters:&character length:1] autorelease];

  NSUInteger modifiers =
      (accelerator->IsCtrlDown() ? NSControlKeyMask : 0) |
      (accelerator->IsCmdDown() ? NSCommandKeyMask : 0) |
      (accelerator->IsAltDown() ? NSAlternateKeyMask : 0) |
      (accelerator->IsShiftDown() ? NSShiftKeyMask : 0);

  scoped_ptr<ui::PlatformAccelerator> platform_accelerator(
      new ui::PlatformAcceleratorCocoa(characters, modifiers));
  accelerator->set_platform_accelerator(std::move(platform_accelerator));
}

}  // namespace accelerator_util

Fix converting from windows virtual keycode back to mac keycode

// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/ui/accelerator_util.h"

#include "ui/base/accelerators/accelerator.h"
#import "ui/base/accelerators/platform_accelerator_cocoa.h"
#import "ui/events/keycodes/keyboard_code_conversion_mac.h"

namespace accelerator_util {

void SetPlatformAccelerator(ui::Accelerator* accelerator) {
  unichar character;
  unichar characterIgnoringModifiers;

  NSUInteger modifiers =
      (accelerator->IsCtrlDown() ? NSControlKeyMask : 0) |
      (accelerator->IsCmdDown() ? NSCommandKeyMask : 0) |
      (accelerator->IsAltDown() ? NSAlternateKeyMask : 0) |
      (accelerator->IsShiftDown() ? NSShiftKeyMask : 0);

  ui::MacKeyCodeForWindowsKeyCode(accelerator->key_code(),
                                  modifiers,
                                  &character,
                                  &characterIgnoringModifiers);

  if (character != characterIgnoringModifiers) {
    modifiers ^= NSShiftKeyMask;
  }

  NSString* characters =
      [[[NSString alloc] initWithCharacters:&character length:1] autorelease];

  scoped_ptr<ui::PlatformAccelerator> platform_accelerator(
      new ui::PlatformAcceleratorCocoa(characters, modifiers));
  accelerator->set_platform_accelerator(std::move(platform_accelerator));
}

}  // namespace accelerator_util


[Desktop Entry]
Type=Application
Name=SeoSplasher
GenericName=Waterballoon game
Comment=Play some SeoSplasher
Icon=SeoSplasher
TryExec=SeoSplasher
Exec=SeoSplasher
Terminal=false
Categories=Game
X-AppImage-Name=SeoSplasher
X-AppImage-Version=1.5
X-AppImage-Arch=x86_64

Update AppImage version to 1.5.1

[Desktop Entry]
Type=Application
Name=SeoSplasher
GenericName=Waterballoon game
Comment=Play some SeoSplasher
Icon=SeoSplasher
TryExec=SeoSplasher
Exec=SeoSplasher
Terminal=false
Categories=Game
X-AppImage-Name=SeoSplasher
X-AppImage-Version=1.5.1
X-AppImage-Arch=x86_64


[Desktop Entry]
Encoding=UTF-8
Icon=highlight
Type=Service
ServiceTypes=KCModule

X-KDE-ModuleType=Library
X-KDE-Library=kcm_kopete_highlight
X-KDE-FactoryName=HighlightConfigFactory
X-KDE-ParentApp=kopete_highlight
X-KDE-ParentComponents=kopete_highlight

Name=Highlight
Name[da]=Fremhæv
Name[sr]=Истицање
Comment=Highlights text based on filters
Comment[da]=Fremhæv tekst baseret på filtre

Make highlight show up in the prefs. You took a bad example, Oliver :)

[Desktop Entry]
Encoding=UTF-8
Icon=highlight
Type=Service
ServiceTypes=KCModule

X-KDE-ModuleType=Library
X-KDE-Library=kopete_highlight
X-KDE-FactoryName=HighlightConfigFactory
X-KDE-ParentApp=kopete_highlight
X-KDE-ParentComponents=kopete_highlight

Name=Highlight
Name[ca]=Ressaltat
Name[da]=Fremhæv
Name[sr]=Истицање
Name[sv]=Markera
Comment=Highlights text based on filters
Comment[ca]=Ressalta el text basant-se en filtres
Comment[da]=Fremhæv tekst baseret på filtre
Comment[sv]=Markerar text baserat på filter