Style: Apply clang-format (3.9.1) to Obj-C++ files

This commit is contained in:
Rémi Verschelde 2017-04-09 14:18:49 +02:00
parent a1a0f021ea
commit 3fd10ff6f0
14 changed files with 638 additions and 703 deletions

View file

@ -31,7 +31,7 @@ PARSE_EXTS=true
# File types to parse. Only effective when PARSE_EXTS is true. # File types to parse. Only effective when PARSE_EXTS is true.
# FILE_EXTS=".c .h .cpp .hpp" # FILE_EXTS=".c .h .cpp .hpp"
FILE_EXTS=".c .h .cpp .hpp .cc .hh .cxx .m" FILE_EXTS=".c .h .cpp .hpp .cc .hh .cxx .m .mm .inc"
# Use pygmentize instead of cat to parse diff with highlighting. # Use pygmentize instead of cat to parse diff with highlighting.
# Install it with `pip install pygments` (Linux) or `easy_install Pygments` (Mac) # Install it with `pip install pygments` (Linux) or `easy_install Pygments` (Mac)

View file

@ -11,7 +11,7 @@ else
RANGE=HEAD RANGE=HEAD
fi fi
FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -v thirdparty/ | grep -e "\.cpp$" -e "\.h$" -e "\.inc$") FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -v thirdparty/ | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|m|mm|inc)$")
echo "Checking files:\n$FILES" echo "Checking files:\n$FILES"
# create a random filename to store our generated patch # create a random filename to store our generated patch

View file

@ -28,11 +28,11 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/ /*************************************************************************/
#import "app_delegate.h" #import "app_delegate.h"
#import "gl_view.h"
#include "os_iphone.h"
#include "core/global_config.h" #include "core/global_config.h"
#import "gl_view.h"
#include "main/main.h" #include "main/main.h"
#include "os_iphone.h"
#ifdef MODULE_FACEBOOKSCORER_IOS_ENABLED #ifdef MODULE_FACEBOOKSCORER_IOS_ENABLED
#include "modules/FacebookScorer_ios/FacebookScorer.h" #include "modules/FacebookScorer_ios/FacebookScorer.h"
@ -45,19 +45,19 @@
#endif #endif
#ifdef MODULE_PARSE_ENABLED #ifdef MODULE_PARSE_ENABLED
#import <Parse/Parse.h>
#import "FBSDKCoreKit/FBSDKCoreKit.h" #import "FBSDKCoreKit/FBSDKCoreKit.h"
#import <Parse/Parse.h>
#endif #endif
#define kFilteringFactor 0.1 #define kFilteringFactor 0.1
#define kRenderingFrequency 60 #define kRenderingFrequency 60
#define kAccelerometerFrequency 100.0 // Hz #define kAccelerometerFrequency 100.0 // Hz
Error _shell_open(String); Error _shell_open(String);
void _set_keep_screen_on(bool p_enabled); void _set_keep_screen_on(bool p_enabled);
Error _shell_open(String p_uri) { Error _shell_open(String p_uri) {
NSString* url = [[NSString alloc] initWithUTF8String:p_uri.utf8().get_data()]; NSString *url = [[NSString alloc] initWithUTF8String:p_uri.utf8().get_data()];
if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]]) if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]])
return ERR_CANT_OPEN; return ERR_CANT_OPEN;
@ -77,20 +77,21 @@ void _set_keep_screen_on(bool p_enabled) {
@synthesize window; @synthesize window;
extern int gargc; extern int gargc;
extern char** gargv; extern char **gargv;
extern int iphone_main(int, int, int, char**); extern int iphone_main(int, int, int, char **);
extern void iphone_finish(); extern void iphone_finish();
CMMotionManager *motionManager; CMMotionManager *motionManager;
bool motionInitialised; bool motionInitialised;
static ViewController* mainViewController = nil; static ViewController *mainViewController = nil;
+ (ViewController*) getViewController { + (ViewController *)getViewController {
return mainViewController; return mainViewController;
} }
static int frame_count = 0; static int frame_count = 0;
- (void)drawView:(GLView*)view; { - (void)drawView:(GLView *)view;
{
switch (frame_count) { switch (frame_count) {
case 0: { case 0: {
@ -111,7 +112,7 @@ static int frame_count = 0;
}; };
++frame_count; ++frame_count;
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *documentsDirectory = [paths objectAtIndex:0];
//NSString *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; //NSString *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
OSIPhone::get_singleton()->set_data_dir(String::utf8([documentsDirectory UTF8String])); OSIPhone::get_singleton()->set_data_dir(String::utf8([documentsDirectory UTF8String]));
@ -119,15 +120,15 @@ static int frame_count = 0;
NSString *locale_code = [[[NSLocale preferredLanguages] objectAtIndex:0] substringToIndex:2]; NSString *locale_code = [[[NSLocale preferredLanguages] objectAtIndex:0] substringToIndex:2];
OSIPhone::get_singleton()->set_locale(String::utf8([locale_code UTF8String])); OSIPhone::get_singleton()->set_locale(String::utf8([locale_code UTF8String]));
NSString* uuid; NSString *uuid;
if ([[UIDevice currentDevice]respondsToSelector:@selector(identifierForVendor)]) { if ([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)]) {
uuid = [UIDevice currentDevice].identifierForVendor.UUIDString; uuid = [UIDevice currentDevice].identifierForVendor.UUIDString;
} else { } else {
// before iOS 6, so just generate an identifier and store it // before iOS 6, so just generate an identifier and store it
uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"identiferForVendor"]; uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"identiferForVendor"];
if( !uuid ) { if (!uuid) {
CFUUIDRef cfuuid = CFUUIDCreate(NULL); CFUUIDRef cfuuid = CFUUIDCreate(NULL);
uuid = (__bridge_transfer NSString*)CFUUIDCreateString(NULL, cfuuid); uuid = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, cfuuid);
CFRelease(cfuuid); CFRelease(cfuuid);
[[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"identifierForVendor"]; [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"identifierForVendor"];
} }
@ -136,7 +137,7 @@ static int frame_count = 0;
OSIPhone::get_singleton()->set_unique_ID(String::utf8([uuid UTF8String])); OSIPhone::get_singleton()->set_unique_ID(String::utf8([uuid UTF8String]));
}; break; }; break;
/* /*
case 1: { case 1: {
++frame_count; ++frame_count;
}; break; }; break;
@ -147,31 +148,31 @@ static int frame_count = 0;
++frame_count; ++frame_count;
// this might be necessary before here // this might be necessary before here
NSDictionary* dict = [[NSBundle mainBundle] infoDictionary]; NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
for (NSString* key in dict) { for (NSString *key in dict) {
NSObject* value = [dict objectForKey:key]; NSObject *value = [dict objectForKey:key];
String ukey = String::utf8([key UTF8String]); String ukey = String::utf8([key UTF8String]);
// we need a NSObject to Variant conversor // we need a NSObject to Variant conversor
if ([value isKindOfClass:[NSString class]]) { if ([value isKindOfClass:[NSString class]]) {
NSString* str = (NSString*)value; NSString *str = (NSString *)value;
String uval = String::utf8([str UTF8String]); String uval = String::utf8([str UTF8String]);
GlobalConfig::get_singleton()->set("Info.plist/"+ukey, uval); GlobalConfig::get_singleton()->set("Info.plist/" + ukey, uval);
} else if ([value isKindOfClass:[NSNumber class]]) { } else if ([value isKindOfClass:[NSNumber class]]) {
NSNumber* n = (NSNumber*)value; NSNumber *n = (NSNumber *)value;
double dval = [n doubleValue]; double dval = [n doubleValue];
GlobalConfig::get_singleton()->set("Info.plist/"+ukey, dval); GlobalConfig::get_singleton()->set("Info.plist/" + ukey, dval);
}; };
// do stuff // do stuff
} }
}; break; }; break;
/* /*
case 3: { case 3: {
++frame_count; ++frame_count;
}; break; }; break;
@ -185,7 +186,7 @@ static int frame_count = 0;
default: { default: {
if (OSIPhone::get_singleton()) { if (OSIPhone::get_singleton()) {
// OSIPhone::get_singleton()->update_accelerometer(accel[0], accel[1], accel[2]); //OSIPhone::get_singleton()->update_accelerometer(accel[0], accel[1], accel[2]);
if (motionInitialised) { if (motionInitialised) {
// Just using polling approach for now, we can set this up so it sends data to us in intervals, might be better. // Just using polling approach for now, we can set this up so it sends data to us in intervals, might be better.
// See Apple reference pages for more details: // See Apple reference pages for more details:
@ -205,7 +206,7 @@ static int frame_count = 0;
// [[UIDevice currentDevice] orientation] changes even if we've fixed our orientation which is not // [[UIDevice currentDevice] orientation] changes even if we've fixed our orientation which is not
// a good thing when you're trying to get your user to move the screen in all directions and want consistent output // a good thing when you're trying to get your user to move the screen in all directions and want consistent output
///@TODO Using [[UIApplication sharedApplication] statusBarOrientation] is a bit of a hack. Godot obviously knows the orientation so maybe we ///@TODO Using [[UIApplication sharedApplication] statusBarOrientation] is a bit of a hack. Godot obviously knows the orientation so maybe we
// can use that instead? (note that left and right seem swapped) // can use that instead? (note that left and right seem swapped)
switch ([[UIApplication sharedApplication] statusBarOrientation]) { switch ([[UIApplication sharedApplication] statusBarOrientation]) {
@ -240,7 +241,6 @@ static int frame_count = 0;
}; };
}; break; }; break;
}; };
}; };
@ -250,7 +250,7 @@ static int frame_count = 0;
OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_MEMORY_WARNING); OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_MEMORY_WARNING);
}; };
- (void)applicationDidFinishLaunching:(UIApplication*)application { - (void)applicationDidFinishLaunching:(UIApplication *)application {
printf("**************** app delegate init\n"); printf("**************** app delegate init\n");
CGRect rect = [[UIScreen mainScreen] bounds]; CGRect rect = [[UIScreen mainScreen] bounds];
@ -283,8 +283,8 @@ static int frame_count = 0;
view_controller.view = glView; view_controller.view = glView;
window.rootViewController = view_controller; window.rootViewController = view_controller;
_set_keep_screen_on(bool(GLOBAL_DEF("display/keep_screen_on",true)) ? YES : NO); _set_keep_screen_on(bool(GLOBAL_DEF("display/keep_screen_on", true)) ? YES : NO);
glView.useCADisplayLink = bool(GLOBAL_DEF("display.iOS/use_cadisplaylink",true)) ? YES : NO; glView.useCADisplayLink = bool(GLOBAL_DEF("display.iOS/use_cadisplaylink", true)) ? YES : NO;
printf("cadisaplylink: %d", glView.useCADisplayLink); printf("cadisaplylink: %d", glView.useCADisplayLink);
glView.animationInterval = 1.0 / kRenderingFrequency; glView.animationInterval = 1.0 / kRenderingFrequency;
[glView startAnimation]; [glView startAnimation];
@ -296,7 +296,7 @@ static int frame_count = 0;
if (!motionInitialised) { if (!motionInitialised) {
motionManager = [[CMMotionManager alloc] init]; motionManager = [[CMMotionManager alloc] init];
if (motionManager.deviceMotionAvailable) { if (motionManager.deviceMotionAvailable) {
motionManager.deviceMotionUpdateInterval = 1.0/70.0; motionManager.deviceMotionUpdateInterval = 1.0 / 70.0;
[motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical]; [motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical];
motionInitialised = YES; motionInitialised = YES;
}; };
@ -316,11 +316,11 @@ static int frame_count = 0;
return; return;
} }
String adid = GLOBAL_DEF("mobileapptracker/advertiser_id",""); String adid = GLOBAL_DEF("mobileapptracker/advertiser_id", "");
String convkey = GLOBAL_DEF("mobileapptracker/conversion_key",""); String convkey = GLOBAL_DEF("mobileapptracker/conversion_key", "");
NSString * advertiser_id = [NSString stringWithUTF8String:adid.utf8().get_data()]; NSString *advertiser_id = [NSString stringWithUTF8String:adid.utf8().get_data()];
NSString * conversion_key = [NSString stringWithUTF8String:convkey.utf8().get_data()]; NSString *conversion_key = [NSString stringWithUTF8String:convkey.utf8().get_data()];
// Account Configuration info - must be set // Account Configuration info - must be set
[MobileAppTracker initializeWithMATAdvertiserId:advertiser_id MATConversionKey:conversion_key]; [MobileAppTracker initializeWithMATAdvertiserId:advertiser_id MATConversionKey:conversion_key];
@ -328,13 +328,12 @@ static int frame_count = 0;
// Used to pass us the IFA, enables highly accurate 1-to-1 attribution. // Used to pass us the IFA, enables highly accurate 1-to-1 attribution.
// Required for many advertising networks. // Required for many advertising networks.
[MobileAppTracker setAppleAdvertisingIdentifier:[[ASIdentifierManager sharedManager] advertisingIdentifier] [MobileAppTracker setAppleAdvertisingIdentifier:[[ASIdentifierManager sharedManager] advertisingIdentifier]
advertisingTrackingEnabled:[[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]]; advertisingTrackingEnabled:[[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]];
#endif #endif
}; };
- (void)applicationWillTerminate:(UIApplication*)application { - (void)applicationWillTerminate:(UIApplication *)application {
printf("********************* will terminate\n"); printf("********************* will terminate\n");
@ -343,7 +342,7 @@ static int frame_count = 0;
[motionManager stopDeviceMotionUpdates]; [motionManager stopDeviceMotionUpdates];
[motionManager release]; [motionManager release];
motionManager = nil; motionManager = nil;
motionInitialised = NO; motionInitialised = NO;
}; };
iphone_finish(); iphone_finish();
@ -368,13 +367,13 @@ static int frame_count = 0;
[view_controller.view startAnimation]; [view_controller.view startAnimation];
} }
- (void) applicationWillResignActive:(UIApplication *)application { - (void)applicationWillResignActive:(UIApplication *)application {
printf("********************* will resign active\n"); printf("********************* will resign active\n");
//OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT); //OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
[view_controller.view stopAnimation]; // FIXME: pause seems to be recommended elsewhere [view_controller.view stopAnimation]; // FIXME: pause seems to be recommended elsewhere
} }
- (void) applicationDidBecomeActive:(UIApplication *)application { - (void)applicationDidBecomeActive:(UIApplication *)application {
printf("********************* did become active\n"); printf("********************* did become active\n");
#ifdef MODULE_GAME_ANALYTICS_ENABLED #ifdef MODULE_GAME_ANALYTICS_ENABLED
printf("********************* mobile app tracker found\n"); printf("********************* mobile app tracker found\n");
@ -401,13 +400,13 @@ static int frame_count = 0;
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
#ifdef MODULE_PARSE_ENABLED #ifdef MODULE_PARSE_ENABLED
NSLog(@"Handling application openURL"); NSLog(@"Handling application openURL");
return [[FBSDKApplicationDelegate sharedInstance] application:application return [[FBSDKApplicationDelegate sharedInstance]
openURL:url application:application
sourceApplication:sourceApplication openURL:url
annotation:annotation]; sourceApplication:sourceApplication
annotation:annotation];
#endif #endif
#ifdef MODULE_FACEBOOKSCORER_IOS_ENABLED #ifdef MODULE_FACEBOOKSCORER_IOS_ENABLED
return [[[FacebookScorer sharedInstance] facebook] handleOpenURL:url]; return [[[FacebookScorer sharedInstance] facebook] handleOpenURL:url];
#else #else

View file

@ -46,7 +46,7 @@ extern "C" {
#import "app_delegate.h" #import "app_delegate.h"
}; };
GameCenter* GameCenter::instance = NULL; GameCenter *GameCenter::instance = NULL;
void GameCenter::_bind_methods() { void GameCenter::_bind_methods() {
ClassDB::bind_method(D_METHOD("connect"), &GameCenter::connect); ClassDB::bind_method(D_METHOD("connect"), &GameCenter::connect);
@ -63,7 +63,6 @@ void GameCenter::_bind_methods() {
ClassDB::bind_method(D_METHOD("pop_pending_event"), &GameCenter::pop_pending_event); ClassDB::bind_method(D_METHOD("pop_pending_event"), &GameCenter::pop_pending_event);
}; };
Error GameCenter::connect() { Error GameCenter::connect() {
//if this class isn't available, game center isn't implemented //if this class isn't available, game center isn't implemented
@ -72,13 +71,16 @@ Error GameCenter::connect() {
return ERR_UNAVAILABLE; return ERR_UNAVAILABLE;
} }
GKLocalPlayer* player = [GKLocalPlayer localPlayer]; GKLocalPlayer *player = [GKLocalPlayer localPlayer];
ERR_FAIL_COND_V(![player respondsToSelector:@selector(authenticateHandler)], ERR_UNAVAILABLE); ERR_FAIL_COND_V(![player respondsToSelector:@selector(authenticateHandler)], ERR_UNAVAILABLE);
ViewController *root_controller=(ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController; ViewController *root_controller = (ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController;
ERR_FAIL_COND_V(!root_controller, FAILED); ERR_FAIL_COND_V(!root_controller, FAILED);
//this handler is called serveral times. first when the view needs to be shown, then again after the view is cancelled or the user logs in. or if the user's already logged in, it's called just once to confirm they're authenticated. This is why no result needs to be specified in the presentViewController phase. in this case, more calls to this function will follow. // This handler is called several times. First when the view needs to be shown, then again
// after the view is cancelled or the user logs in. Or if the user's already logged in, it's
// called just once to confirm they're authenticated. This is why no result needs to be specified
// in the presentViewController phase. In this case, more calls to this function will follow.
player.authenticateHandler = (^(UIViewController *controller, NSError *error) { player.authenticateHandler = (^(UIViewController *controller, NSError *error) {
if (controller) { if (controller) {
[root_controller presentViewController:controller animated:YES completion:nil]; [root_controller presentViewController:controller animated:YES completion:nil];
@ -113,26 +115,27 @@ Error GameCenter::post_score(Variant p_score) {
float score = params["score"]; float score = params["score"];
String category = params["category"]; String category = params["category"];
NSString* cat_str = [[[NSString alloc] initWithUTF8String:category.utf8().get_data()] autorelease]; NSString *cat_str = [[[NSString alloc] initWithUTF8String:category.utf8().get_data()] autorelease];
GKScore* reporter = [[[GKScore alloc] initWithCategory:cat_str] autorelease]; GKScore *reporter = [[[GKScore alloc] initWithCategory:cat_str] autorelease];
reporter.value = score; reporter.value = score;
ERR_FAIL_COND_V([GKScore respondsToSelector:@selector(reportScores)], ERR_UNAVAILABLE); ERR_FAIL_COND_V([GKScore respondsToSelector:@selector(reportScores)], ERR_UNAVAILABLE);
[GKScore reportScores:@[reporter] withCompletionHandler:^(NSError* error) { [GKScore reportScores:@[ reporter ]
withCompletionHandler:^(NSError *error) {
Dictionary ret; Dictionary ret;
ret["type"] = "post_score"; ret["type"] = "post_score";
if (error == nil) { if (error == nil) {
ret["result"] = "ok"; ret["result"] = "ok";
} else { } else {
ret["result"] = "error"; ret["result"] = "error";
ret["error_code"] = error.code; ret["error_code"] = error.code;
ret["error_description"] = [error.localizedDescription UTF8String]; ret["error_description"] = [error.localizedDescription UTF8String];
}; };
pending_events.push_back(ret); pending_events.push_back(ret);
}]; }];
return OK; return OK;
}; };
@ -144,8 +147,8 @@ Error GameCenter::award_achievement(Variant p_params) {
String name = params["name"]; String name = params["name"];
float progress = params["progress"]; float progress = params["progress"];
NSString* name_str = [[[NSString alloc] initWithUTF8String:name.utf8().get_data()] autorelease]; NSString *name_str = [[[NSString alloc] initWithUTF8String:name.utf8().get_data()] autorelease];
GKAchievement* achievement = [[[GKAchievement alloc] initWithIdentifier: name_str] autorelease]; GKAchievement *achievement = [[[GKAchievement alloc] initWithIdentifier:name_str] autorelease];
ERR_FAIL_COND_V(!achievement, FAILED); ERR_FAIL_COND_V(!achievement, FAILED);
ERR_FAIL_COND_V([GKAchievement respondsToSelector:@selector(reportAchievements)], ERR_UNAVAILABLE); ERR_FAIL_COND_V([GKAchievement respondsToSelector:@selector(reportAchievements)], ERR_UNAVAILABLE);
@ -156,19 +159,20 @@ Error GameCenter::award_achievement(Variant p_params) {
achievement.showsCompletionBanner = params["show_completion_banner"] ? YES : NO; achievement.showsCompletionBanner = params["show_completion_banner"] ? YES : NO;
} }
[GKAchievement reportAchievements:@[achievement] withCompletionHandler:^(NSError *error) { [GKAchievement reportAchievements:@[ achievement ]
withCompletionHandler:^(NSError *error) {
Dictionary ret; Dictionary ret;
ret["type"] = "award_achievement"; ret["type"] = "award_achievement";
if (error == nil) { if (error == nil) {
ret["result"] = "ok"; ret["result"] = "ok";
} else { } else {
ret["result"] = "error"; ret["result"] = "error";
ret["error_code"] = error.code; ret["error_code"] = error.code;
}; };
pending_events.push_back(ret); pending_events.push_back(ret);
}]; }];
return OK; return OK;
}; };
@ -191,9 +195,9 @@ void GameCenter::request_achievement_descriptions() {
for (int i = 0; i < [descriptions count]; i++) { for (int i = 0; i < [descriptions count]; i++) {
GKAchievementDescription* description = [descriptions objectAtIndex:i]; GKAchievementDescription *description = [descriptions objectAtIndex:i];
const char* str = [description.identifier UTF8String]; const char *str = [description.identifier UTF8String];
names.push_back(String::utf8(str != NULL ? str : "")); names.push_back(String::utf8(str != NULL ? str : ""));
str = [description.title UTF8String]; str = [description.title UTF8String];
@ -229,7 +233,6 @@ void GameCenter::request_achievement_descriptions() {
}]; }];
}; };
void GameCenter::request_achievements() { void GameCenter::request_achievements() {
[GKAchievement loadAchievementsWithCompletionHandler:^(NSArray *achievements, NSError *error) { [GKAchievement loadAchievementsWithCompletionHandler:^(NSArray *achievements, NSError *error) {
@ -241,10 +244,10 @@ void GameCenter::request_achievements() {
PoolStringArray names; PoolStringArray names;
PoolRealArray percentages; PoolRealArray percentages;
for (int i=0; i<[achievements count]; i++) { for (int i = 0; i < [achievements count]; i++) {
GKAchievement* achievement = [achievements objectAtIndex:i]; GKAchievement *achievement = [achievements objectAtIndex:i];
const char* str = [achievement.identifier UTF8String]; const char *str = [achievement.identifier UTF8String];
names.push_back(String::utf8(str != NULL ? str : "")); names.push_back(String::utf8(str != NULL ? str : ""));
percentages.push_back(achievement.percentComplete); percentages.push_back(achievement.percentComplete);
@ -303,7 +306,7 @@ Error GameCenter::show_game_center(Variant p_params) {
GKGameCenterViewController *controller = [[GKGameCenterViewController alloc] init]; GKGameCenterViewController *controller = [[GKGameCenterViewController alloc] init];
ERR_FAIL_COND_V(!controller, FAILED); ERR_FAIL_COND_V(!controller, FAILED);
ViewController *root_controller=(ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController; ViewController *root_controller = (ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController;
ERR_FAIL_COND_V(!root_controller, FAILED); ERR_FAIL_COND_V(!root_controller, FAILED);
controller.gameCenterDelegate = root_controller; controller.gameCenterDelegate = root_controller;
@ -312,12 +315,12 @@ Error GameCenter::show_game_center(Variant p_params) {
controller.leaderboardIdentifier = nil; controller.leaderboardIdentifier = nil;
if (params.has("leaderboard_name")) { if (params.has("leaderboard_name")) {
String name = params["leaderboard_name"]; String name = params["leaderboard_name"];
NSString* name_str = [[[NSString alloc] initWithUTF8String:name.utf8().get_data()] autorelease]; NSString *name_str = [[[NSString alloc] initWithUTF8String:name.utf8().get_data()] autorelease];
controller.leaderboardIdentifier = name_str; controller.leaderboardIdentifier = name_str;
} }
} }
[root_controller presentViewController: controller animated: YES completion:nil]; [root_controller presentViewController:controller animated:YES completion:nil];
return OK; return OK;
}; };
@ -325,7 +328,7 @@ Error GameCenter::show_game_center(Variant p_params) {
void GameCenter::game_center_closed() { void GameCenter::game_center_closed() {
Dictionary ret; Dictionary ret;
ret["type"] = "show_game_center"; ret["type"] = "show_game_center";
ret["result"] = "ok"; ret["result"] = "ok";
pending_events.push_back(ret); pending_events.push_back(ret);
} }
@ -343,7 +346,7 @@ Variant GameCenter::pop_pending_event() {
return front; return front;
}; };
GameCenter* GameCenter::get_singleton() { GameCenter *GameCenter::get_singleton() {
return instance; return instance;
}; };
@ -353,9 +356,6 @@ GameCenter::GameCenter() {
connected = false; connected = false;
}; };
GameCenter::~GameCenter(){};
GameCenter::~GameCenter() {
};
#endif #endif

181
platform/iphone/gl_view.mm Executable file → Normal file
View file

@ -27,15 +27,15 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/ /*************************************************************************/
#import "gl_view.h"
#import <QuartzCore/QuartzCore.h>
#import <OpenGLES/EAGLDrawable.h>
#include "os_iphone.h"
#include "core/os/keyboard.h"
#include "core/global_config.h" #include "core/global_config.h"
#include "core/os/keyboard.h"
#include "os_iphone.h"
#include "servers/audio_server.h" #include "servers/audio_server.h"
#import "gl_view.h" #import <OpenGLES/EAGLDrawable.h>
#import <QuartzCore/QuartzCore.h>
/* /*
@interface GLView (private) @interface GLView (private)
@ -48,7 +48,7 @@
int gl_view_base_fb; int gl_view_base_fb;
static String keyboard_text; static String keyboard_text;
static GLView* _instance = NULL; static GLView *_instance = NULL;
static bool video_found_error = false; static bool video_found_error = false;
static bool video_playing = false; static bool video_playing = false;
@ -79,21 +79,22 @@ void _hide_keyboard() {
bool _play_video(String p_path, float p_volume, String p_audio_track, String p_subtitle_track) { bool _play_video(String p_path, float p_volume, String p_audio_track, String p_subtitle_track) {
p_path = GlobalConfig::get_singleton()->globalize_path(p_path); p_path = GlobalConfig::get_singleton()->globalize_path(p_path);
NSString* file_path = [[[NSString alloc] initWithUTF8String:p_path.utf8().get_data()] autorelease]; NSString *file_path = [[[NSString alloc] initWithUTF8String:p_path.utf8().get_data()] autorelease];
_instance.avAsset = [AVAsset assetWithURL:[NSURL fileURLWithPath:file_path]]; _instance.avAsset = [AVAsset assetWithURL:[NSURL fileURLWithPath:file_path]];
_instance.avPlayerItem =[[AVPlayerItem alloc]initWithAsset:_instance.avAsset]; _instance.avPlayerItem = [[AVPlayerItem alloc] initWithAsset:_instance.avAsset];
[_instance.avPlayerItem addObserver:_instance forKeyPath:@"status" options:0 context:nil]; [_instance.avPlayerItem addObserver:_instance forKeyPath:@"status" options:0 context:nil];
_instance.avPlayer = [[AVPlayer alloc]initWithPlayerItem:_instance.avPlayerItem]; _instance.avPlayer = [[AVPlayer alloc] initWithPlayerItem:_instance.avPlayerItem];
_instance.avPlayerLayer =[AVPlayerLayer playerLayerWithPlayer:_instance.avPlayer]; _instance.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:_instance.avPlayer];
[_instance.avPlayer addObserver:_instance forKeyPath:@"status" options:0 context:nil]; [_instance.avPlayer addObserver:_instance forKeyPath:@"status" options:0 context:nil];
[[NSNotificationCenter defaultCenter] addObserver:_instance [[NSNotificationCenter defaultCenter]
selector:@selector(playerItemDidReachEnd:) addObserver:_instance
name:AVPlayerItemDidPlayToEndTimeNotification selector:@selector(playerItemDidReachEnd:)
object:[_instance.avPlayer currentItem]]; name:AVPlayerItemDidPlayToEndTimeNotification
object:[_instance.avPlayer currentItem]];
[_instance.avPlayer addObserver:_instance forKeyPath:@"rate" options:NSKeyValueObservingOptionNew context:0]; [_instance.avPlayer addObserver:_instance forKeyPath:@"rate" options:NSKeyValueObservingOptionNew context:0];
@ -101,11 +102,11 @@ bool _play_video(String p_path, float p_volume, String p_audio_track, String p_s
[_instance.layer addSublayer:_instance.avPlayerLayer]; [_instance.layer addSublayer:_instance.avPlayerLayer];
[_instance.avPlayer play]; [_instance.avPlayer play];
AVMediaSelectionGroup *audioGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic: AVMediaCharacteristicAudible]; AVMediaSelectionGroup *audioGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicAudible];
NSMutableArray *allAudioParams = [NSMutableArray array]; NSMutableArray *allAudioParams = [NSMutableArray array];
for (id track in audioGroup.options) { for (id track in audioGroup.options) {
NSString* language = [[track locale] localeIdentifier]; NSString *language = [[track locale] localeIdentifier];
NSLog(@"subtitle lang: %@", language); NSLog(@"subtitle lang: %@", language);
if ([language isEqualToString:[NSString stringWithUTF8String:p_audio_track.utf8()]]) { if ([language isEqualToString:[NSString stringWithUTF8String:p_audio_track.utf8()]]) {
@ -117,22 +118,22 @@ bool _play_video(String p_path, float p_volume, String p_audio_track, String p_s
AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix]; AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
[audioMix setInputParameters:allAudioParams]; [audioMix setInputParameters:allAudioParams];
[_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup: audioGroup]; [_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup:audioGroup];
[_instance.avPlayer.currentItem setAudioMix:audioMix]; [_instance.avPlayer.currentItem setAudioMix:audioMix];
break; break;
} }
} }
AVMediaSelectionGroup *subtitlesGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic: AVMediaCharacteristicLegible]; AVMediaSelectionGroup *subtitlesGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicLegible];
NSArray *useableTracks = [AVMediaSelectionGroup mediaSelectionOptionsFromArray:subtitlesGroup.options withoutMediaCharacteristics:[NSArray arrayWithObject:AVMediaCharacteristicContainsOnlyForcedSubtitles]]; NSArray *useableTracks = [AVMediaSelectionGroup mediaSelectionOptionsFromArray:subtitlesGroup.options withoutMediaCharacteristics:[NSArray arrayWithObject:AVMediaCharacteristicContainsOnlyForcedSubtitles]];
for (id track in useableTracks) { for (id track in useableTracks) {
NSString* language = [[track locale] localeIdentifier]; NSString *language = [[track locale] localeIdentifier];
NSLog(@"subtitle lang: %@", language); NSLog(@"subtitle lang: %@", language);
if ([language isEqualToString:[NSString stringWithUTF8String:p_subtitle_track.utf8()]]) { if ([language isEqualToString:[NSString stringWithUTF8String:p_subtitle_track.utf8()]]) {
[_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup: subtitlesGroup]; [_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup:subtitlesGroup];
break; break;
} }
} }
@ -178,19 +179,19 @@ void _stop_video() {
@synthesize animationInterval; @synthesize animationInterval;
static const int max_touches = 8; static const int max_touches = 8;
static UITouch* touches[max_touches]; static UITouch *touches[max_touches];
static void init_touches() { static void init_touches() {
for (int i=0; i<max_touches; i++) { for (int i = 0; i < max_touches; i++) {
touches[i] = NULL; touches[i] = NULL;
}; };
}; };
static int get_touch_id(UITouch* p_touch) { static int get_touch_id(UITouch *p_touch) {
int first = -1; int first = -1;
for (int i=0; i<max_touches; i++) { for (int i = 0; i < max_touches; i++) {
if (first == -1 && touches[i] == NULL) { if (first == -1 && touches[i] == NULL) {
first = i; first = i;
continue; continue;
@ -207,10 +208,10 @@ static int get_touch_id(UITouch* p_touch) {
return -1; return -1;
}; };
static int remove_touch(UITouch* p_touch) { static int remove_touch(UITouch *p_touch) {
int remaining = 0; int remaining = 0;
for (int i=0; i<max_touches; i++) { for (int i = 0; i < max_touches; i++) {
if (touches[i] == NULL) if (touches[i] == NULL)
continue; continue;
@ -222,9 +223,9 @@ static int remove_touch(UITouch* p_touch) {
return remaining; return remaining;
}; };
static int get_first_id(UITouch* p_touch) { static int get_first_id(UITouch *p_touch) {
for (int i=0; i<max_touches; i++) { for (int i = 0; i < max_touches; i++) {
if (touches[i] != NULL) if (touches[i] != NULL)
return i; return i;
@ -234,7 +235,7 @@ static int get_first_id(UITouch* p_touch) {
static void clear_touches() { static void clear_touches() {
for (int i=0; i<max_touches; i++) { for (int i = 0; i < max_touches; i++) {
touches[i] = NULL; touches[i] = NULL;
}; };
@ -242,35 +243,36 @@ static void clear_touches() {
// Implement this to override the default layer class (which is [CALayer class]). // Implement this to override the default layer class (which is [CALayer class]).
// We do this so that our view will be backed by a layer that is capable of OpenGL ES rendering. // We do this so that our view will be backed by a layer that is capable of OpenGL ES rendering.
+ (Class) layerClass { + (Class)layerClass {
return [CAEAGLLayer class]; return [CAEAGLLayer class];
} }
//The GL view is stored in the nib file. When it's unarchived it's sent -initWithCoder: //The GL view is stored in the nib file. When it's unarchived it's sent -initWithCoder:
- (id)initWithCoder:(NSCoder*)coder { - (id)initWithCoder:(NSCoder *)coder {
active = FALSE; active = FALSE;
if((self = [super initWithCoder:coder])) if ((self = [super initWithCoder:coder])) {
{
self = [self initGLES]; self = [self initGLES];
} }
return self; return self;
} }
-(id)initGLES { - (id)initGLES {
// Get our backing layer // Get our backing layer
CAEAGLLayer *eaglLayer = (CAEAGLLayer*) self.layer; CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
// Configure it so that it is opaque, does not retain the contents of the backbuffer when displayed, and uses RGBA8888 color. // Configure it so that it is opaque, does not retain the contents of the backbuffer when displayed, and uses RGBA8888 color.
eaglLayer.opaque = YES; eaglLayer.opaque = YES;
eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: eaglLayer.drawableProperties = [NSDictionary
[NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:FALSE],
kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, kEAGLDrawablePropertyRetainedBacking,
nil]; kEAGLColorFormatRGBA8,
kEAGLDrawablePropertyColorFormat,
nil];
// Create our EAGLContext, and if successful make it current and create our framebuffer. // Create our EAGLContext, and if successful make it current and create our framebuffer.
context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3]; context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
if(!context || ![EAGLContext setCurrentContext:context] || ![self createFramebuffer]) { if (!context || ![EAGLContext setCurrentContext:context] || ![self createFramebuffer]) {
[self release]; [self release];
return nil; return nil;
} }
@ -280,12 +282,12 @@ static void clear_touches() {
return self; return self;
} }
-(id<GLViewDelegate>)delegate { - (id<GLViewDelegate>)delegate {
return delegate; return delegate;
} }
// Update the delegate, and if it needs a -setupView: call, set our internal flag so that it will be called. // Update the delegate, and if it needs a -setupView: call, set our internal flag so that it will be called.
-(void)setDelegate:(id<GLViewDelegate>)d { - (void)setDelegate:(id<GLViewDelegate>)d {
delegate = d; delegate = d;
delegateSetup = ![delegate respondsToSelector:@selector(setupView:)]; delegateSetup = ![delegate respondsToSelector:@selector(setupView:)];
} }
@ -296,19 +298,18 @@ static void clear_touches() {
// This is the perfect opportunity to also update the framebuffer so that it is // This is the perfect opportunity to also update the framebuffer so that it is
// the same size as our display area. // the same size as our display area.
-(void)layoutSubviews { - (void)layoutSubviews {
//printf("HERE\n"); //printf("HERE\n");
[EAGLContext setCurrentContext:context]; [EAGLContext setCurrentContext:context];
[self destroyFramebuffer]; [self destroyFramebuffer];
[self createFramebuffer]; [self createFramebuffer];
[self drawView]; [self drawView];
[self drawView]; [self drawView];
} }
- (BOOL)createFramebuffer { - (BOOL)createFramebuffer {
// Generate IDs for a framebuffer object and a color renderbuffer // Generate IDs for a framebuffer object and a color renderbuffer
UIScreen* mainscr = [UIScreen mainScreen]; UIScreen *mainscr = [UIScreen mainScreen];
printf("******** screen size %i, %i\n", (int)mainscr.currentMode.size.width, (int)mainscr.currentMode.size.height); printf("******** screen size %i, %i\n", (int)mainscr.currentMode.size.width, (int)mainscr.currentMode.size.height);
float minPointSize = MIN(mainscr.bounds.size.width, mainscr.bounds.size.height); float minPointSize = MIN(mainscr.bounds.size.width, mainscr.bounds.size.height);
float minScreenSize = MIN(mainscr.currentMode.size.width, mainscr.currentMode.size.height); float minScreenSize = MIN(mainscr.currentMode.size.width, mainscr.currentMode.size.height);
@ -333,7 +334,7 @@ static void clear_touches() {
glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight); glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer); glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) { if (glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES)); NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
return NO; return NO;
} }
@ -359,8 +360,7 @@ static void clear_touches() {
glDeleteRenderbuffersOES(1, &viewRenderbuffer); glDeleteRenderbuffersOES(1, &viewRenderbuffer);
viewRenderbuffer = 0; viewRenderbuffer = 0;
if(depthRenderbuffer) if (depthRenderbuffer) {
{
glDeleteRenderbuffersOES(1, &depthRenderbuffer); glDeleteRenderbuffersOES(1, &depthRenderbuffer);
depthRenderbuffer = 0; depthRenderbuffer = 0;
} }
@ -375,7 +375,7 @@ static void clear_touches() {
// Approximate frame rate // Approximate frame rate
// assumes device refreshes at 60 fps // assumes device refreshes at 60 fps
int frameInterval = (int) floor(animationInterval * 60.0f); int frameInterval = (int)floor(animationInterval * 60.0f);
displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawView)]; displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawView)];
[displayLink setFrameInterval:frameInterval]; [displayLink setFrameInterval:frameInterval];
@ -414,7 +414,7 @@ static void clear_touches() {
- (void)setAnimationInterval:(NSTimeInterval)interval { - (void)setAnimationInterval:(NSTimeInterval)interval {
animationInterval = interval; animationInterval = interval;
if ( (useCADisplayLink && displayLink) || ( !useCADisplayLink && animationTimer ) ) { if ((useCADisplayLink && displayLink) || (!useCADisplayLink && animationTimer)) {
[self stopAnimation]; [self stopAnimation];
[self startAnimation]; [self startAnimation];
} }
@ -424,13 +424,14 @@ static void clear_touches() {
- (void)drawView { - (void)drawView {
if (useCADisplayLink) { if (useCADisplayLink) {
// Pause the CADisplayLink to avoid recursion // Pause the CADisplayLink to avoid recursion
[displayLink setPaused: YES]; [displayLink setPaused:YES];
// Process all input events // Process all input events
while(CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource); while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource)
;
// We are good to go, resume the CADisplayLink // We are good to go, resume the CADisplayLink
[displayLink setPaused: NO]; [displayLink setPaused:NO];
} }
if (!active) { if (!active) {
@ -442,7 +443,7 @@ static void clear_touches() {
[EAGLContext setCurrentContext:context]; [EAGLContext setCurrentContext:context];
// If our drawing delegate needs to have the view setup, then call -setupView: and flag that it won't need to be called again. // If our drawing delegate needs to have the view setup, then call -setupView: and flag that it won't need to be called again.
if(!delegateSetup) { if (!delegateSetup) {
[delegate setupView:self]; [delegate setupView:self];
delegateSetup = YES; delegateSetup = YES;
} }
@ -456,18 +457,18 @@ static void clear_touches() {
#ifdef DEBUG_ENABLED #ifdef DEBUG_ENABLED
GLenum err = glGetError(); GLenum err = glGetError();
if(err) if (err)
NSLog(@"%x error", err); NSLog(@"%x error", err);
#endif #endif
} }
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray* tlist = [[event allTouches] allObjects]; NSArray *tlist = [[event allTouches] allObjects];
for (unsigned int i=0; i< [tlist count]; i++) { for (unsigned int i = 0; i < [tlist count]; i++) {
if ( [touches containsObject:[tlist objectAtIndex:i]] ) { if ([touches containsObject:[tlist objectAtIndex:i]]) {
UITouch* touch = [tlist objectAtIndex:i]; UITouch *touch = [tlist objectAtIndex:i];
if (touch.phase != UITouchPhaseBegan) if (touch.phase != UITouchPhaseBegan)
continue; continue;
int tid = get_touch_id(touch); int tid = get_touch_id(touch);
@ -480,12 +481,12 @@ static void clear_touches() {
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray* tlist = [[event allTouches] allObjects]; NSArray *tlist = [[event allTouches] allObjects];
for (unsigned int i=0; i< [tlist count]; i++) { for (unsigned int i = 0; i < [tlist count]; i++) {
if ( [touches containsObject:[tlist objectAtIndex:i]] ) { if ([touches containsObject:[tlist objectAtIndex:i]]) {
UITouch* touch = [tlist objectAtIndex:i]; UITouch *touch = [tlist objectAtIndex:i];
if (touch.phase != UITouchPhaseMoved) if (touch.phase != UITouchPhaseMoved)
continue; continue;
int tid = get_touch_id(touch); int tid = get_touch_id(touch);
@ -496,16 +497,15 @@ static void clear_touches() {
OSIPhone::get_singleton()->mouse_move(tid, prev_point.x * self.contentScaleFactor, prev_point.y * self.contentScaleFactor, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, first == tid); OSIPhone::get_singleton()->mouse_move(tid, prev_point.x * self.contentScaleFactor, prev_point.y * self.contentScaleFactor, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, first == tid);
}; };
}; };
} }
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray* tlist = [[event allTouches] allObjects]; NSArray *tlist = [[event allTouches] allObjects];
for (unsigned int i=0; i< [tlist count]; i++) { for (unsigned int i = 0; i < [tlist count]; i++) {
if ( [touches containsObject:[tlist objectAtIndex:i]] ) { if ([touches containsObject:[tlist objectAtIndex:i]]) {
UITouch* touch = [tlist objectAtIndex:i]; UITouch *touch = [tlist objectAtIndex:i];
if (touch.phase != UITouchPhaseEnded) if (touch.phase != UITouchPhaseEnded)
continue; continue;
int tid = get_touch_id(touch); int tid = get_touch_id(touch);
@ -527,7 +527,6 @@ static void clear_touches() {
return YES; return YES;
}; };
- (void)open_keyboard { - (void)open_keyboard {
//keyboard_text = p_existing; //keyboard_text = p_existing;
[self becomeFirstResponder]; [self becomeFirstResponder];
@ -552,11 +551,11 @@ static void clear_touches() {
String character; String character;
character.parse_utf8([p_text UTF8String]); character.parse_utf8([p_text UTF8String]);
keyboard_text = keyboard_text + character; keyboard_text = keyboard_text + character;
OSIPhone::get_singleton()->key(character[0] == 10 ? KEY_ENTER : character[0] , true); OSIPhone::get_singleton()->key(character[0] == 10 ? KEY_ENTER : character[0], true);
printf("inserting text with character %i\n", character[0]); printf("inserting text with character %i\n", character[0]);
}; };
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification { - (void)audioRouteChangeListenerCallback:(NSNotification *)notification {
printf("*********** route changed!\n"); printf("*********** route changed!\n");
NSDictionary *interuptionDict = notification.userInfo; NSDictionary *interuptionDict = notification.userInfo;
@ -575,8 +574,8 @@ static void clear_touches() {
if (_is_video_playing()) { if (_is_video_playing()) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5f * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5f * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[_instance.avPlayer play]; // NOTE: change this line according your current player implementation [_instance.avPlayer play]; // NOTE: change this line according your current player implementation
NSLog(@"resumed play"); NSLog(@"resumed play");
}); });
}; };
}; break; }; break;
@ -588,24 +587,24 @@ static void clear_touches() {
} }
} }
// When created via code however, we get initWithFrame // When created via code however, we get initWithFrame
-(id)initWithFrame:(CGRect)frame { - (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame]; self = [super initWithFrame:frame];
_instance = self; _instance = self;
printf("after init super %p\n", self); printf("after init super %p\n", self);
if(self != nil) if (self != nil) {
{
self = [self initGLES]; self = [self initGLES];
printf("after init gles %p\n", self); printf("after init gles %p\n", self);
} }
init_touches(); init_touches();
self. multipleTouchEnabled = YES; self.multipleTouchEnabled = YES;
printf("******** adding observer for sound routing changes\n"); printf("******** adding observer for sound routing changes\n");
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) [[NSNotificationCenter defaultCenter]
name:AVAudioSessionRouteChangeNotification addObserver:self
object:nil]; selector:@selector(audioRouteChangeListenerCallback:)
name:AVAudioSessionRouteChangeNotification
object:nil];
//self.autoresizesSubviews = YES; //self.autoresizesSubviews = YES;
//[self setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth]; //[self setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth];
@ -625,7 +624,7 @@ static void clear_touches() {
- (void)dealloc { - (void)dealloc {
[self stopAnimation]; [self stopAnimation];
if([EAGLContext currentContext] == context) { if ([EAGLContext currentContext] == context) {
[EAGLContext setCurrentContext:nil]; [EAGLContext setCurrentContext:nil];
} }
@ -640,17 +639,17 @@ static void clear_touches() {
if (object == _instance.avPlayerItem && [keyPath isEqualToString:@"status"]) { if (object == _instance.avPlayerItem && [keyPath isEqualToString:@"status"]) {
if (_instance.avPlayerItem.status == AVPlayerStatusFailed || _instance.avPlayer.status == AVPlayerStatusFailed) { if (_instance.avPlayerItem.status == AVPlayerStatusFailed || _instance.avPlayer.status == AVPlayerStatusFailed) {
_stop_video(); _stop_video();
video_found_error = true; video_found_error = true;
} }
if(_instance.avPlayer.status == AVPlayerStatusReadyToPlay && if (_instance.avPlayer.status == AVPlayerStatusReadyToPlay &&
_instance.avPlayerItem.status == AVPlayerItemStatusReadyToPlay && _instance.avPlayerItem.status == AVPlayerItemStatusReadyToPlay &&
CMTIME_COMPARE_INLINE(video_current_time, ==, kCMTimeZero)) { CMTIME_COMPARE_INLINE(video_current_time, ==, kCMTimeZero)) {
//NSLog(@"time: %@", video_current_time); //NSLog(@"time: %@", video_current_time);
[_instance.avPlayer seekToTime:video_current_time]; [_instance.avPlayer seekToTime:video_current_time];
video_current_time = kCMTimeZero; video_current_time = kCMTimeZero;
} }
} }
@ -658,8 +657,8 @@ static void clear_touches() {
NSLog(@"Player playback rate changed: %.5f", _instance.avPlayer.rate); NSLog(@"Player playback rate changed: %.5f", _instance.avPlayer.rate);
if (_is_video_playing() && _instance.avPlayer.rate == 0.0 && !_instance.avPlayer.error) { if (_is_video_playing() && _instance.avPlayer.rate == 0.0 && !_instance.avPlayer.error) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5f * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5f * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[_instance.avPlayer play]; // NOTE: change this line according your current player implementation [_instance.avPlayer play]; // NOTE: change this line according your current player implementation
NSLog(@"resumed play"); NSLog(@"resumed play");
}); });
NSLog(@" . . . PAUSED (or just started)"); NSLog(@" . . . PAUSED (or just started)");
@ -668,7 +667,7 @@ static void clear_touches() {
} }
- (void)playerItemDidReachEnd:(NSNotification *)notification { - (void)playerItemDidReachEnd:(NSNotification *)notification {
_stop_video(); _stop_video();
} }
/* /*

View file

@ -35,14 +35,15 @@
extern "C" { extern "C" {
#endif #endif
#import <Foundation/Foundation.h>
#import "app_delegate.h" #import "app_delegate.h"
#import <Foundation/Foundation.h>
#ifndef __IPHONE_9_0 #ifndef __IPHONE_9_0
}; };
#endif #endif
ICloud* ICloud::instance = NULL; ICloud *ICloud::instance = NULL;
void ICloud::_bind_methods() { void ICloud::_bind_methods() {
ClassDB::bind_method(D_METHOD("remove_key"), &ICloud::remove_key); ClassDB::bind_method(D_METHOD("remove_key"), &ICloud::remove_key);
@ -68,18 +69,18 @@ Variant ICloud::pop_pending_event() {
return front; return front;
}; };
ICloud* ICloud::get_singleton() { ICloud *ICloud::get_singleton() {
return instance; return instance;
}; };
//convert from apple's abstract type to godot's abstract type.... //convert from apple's abstract type to godot's abstract type....
Variant nsobject_to_variant(NSObject* object) { Variant nsobject_to_variant(NSObject *object) {
if ([object isKindOfClass:[NSString class]]) { if ([object isKindOfClass:[NSString class]]) {
const char* str = [(NSString*)object UTF8String]; const char *str = [(NSString *)object UTF8String];
return String::utf8(str != NULL ? str : ""); return String::utf8(str != NULL ? str : "");
} else if ([object isKindOfClass:[NSData class]]) { } else if ([object isKindOfClass:[NSData class]]) {
PoolByteArray ret; PoolByteArray ret;
NSData* data = (NSData*)object; NSData *data = (NSData *)object;
if ([data length] > 0) { if ([data length] > 0) {
ret.resize([data length]); ret.resize([data length]);
{ {
@ -90,22 +91,21 @@ Variant nsobject_to_variant(NSObject* object) {
return ret; return ret;
} else if ([object isKindOfClass:[NSArray class]]) { } else if ([object isKindOfClass:[NSArray class]]) {
Array result; Array result;
NSArray* array = (NSArray*)object; NSArray *array = (NSArray *)object;
for (unsigned int i = 0; i < [array count]; ++i) { for (unsigned int i = 0; i < [array count]; ++i) {
NSObject* value = [array objectAtIndex:i]; NSObject *value = [array objectAtIndex:i];
result.push_back(nsobject_to_variant(value)); result.push_back(nsobject_to_variant(value));
} }
return result; return result;
} else if ([object isKindOfClass:[NSDictionary class]]) { } else if ([object isKindOfClass:[NSDictionary class]]) {
Dictionary result; Dictionary result;
NSDictionary* dic = (NSDictionary*)object; NSDictionary *dic = (NSDictionary *)object;
NSArray *keys = [dic allKeys];
NSArray* keys = [dic allKeys];
int count = [keys count]; int count = [keys count];
for (int i=0; i < count; ++i) { for (int i = 0; i < count; ++i) {
NSObject* k = [ keys objectAtIndex:i]; NSObject *k = [keys objectAtIndex:i];
NSObject* v = [dic objectForKey:k]; NSObject *v = [dic objectForKey:k];
result[nsobject_to_variant(k)] = nsobject_to_variant(v); result[nsobject_to_variant(k)] = nsobject_to_variant(v);
} }
@ -115,20 +115,20 @@ Variant nsobject_to_variant(NSObject* object) {
//To avoid errors, we'll cast as broadly as possible, and only return int or float. //To avoid errors, we'll cast as broadly as possible, and only return int or float.
//bool, char, int, uint, longlong -> int //bool, char, int, uint, longlong -> int
//float, double -> float //float, double -> float
NSNumber* num = (NSNumber*)object; NSNumber *num = (NSNumber *)object;
if(strcmp([num objCType], @encode(BOOL)) == 0) { if (strcmp([num objCType], @encode(BOOL)) == 0) {
return Variant((int)[num boolValue]); return Variant((int)[num boolValue]);
} else if(strcmp([num objCType], @encode(char)) == 0) { } else if (strcmp([num objCType], @encode(char)) == 0) {
return Variant((int)[num charValue]); return Variant((int)[num charValue]);
} else if(strcmp([num objCType], @encode(int)) == 0) { } else if (strcmp([num objCType], @encode(int)) == 0) {
return Variant([num intValue]); return Variant([num intValue]);
} else if(strcmp([num objCType], @encode(unsigned int)) == 0) { } else if (strcmp([num objCType], @encode(unsigned int)) == 0) {
return Variant((int)[num unsignedIntValue]); return Variant((int)[num unsignedIntValue]);
} else if(strcmp([num objCType], @encode(long long)) == 0) { } else if (strcmp([num objCType], @encode(long long)) == 0) {
return Variant((int)[num longValue]); return Variant((int)[num longValue]);
} else if(strcmp([num objCType], @encode(float)) == 0) { } else if (strcmp([num objCType], @encode(float)) == 0) {
return Variant([num floatValue]); return Variant([num floatValue]);
} else if(strcmp([num objCType], @encode(double)) == 0) { } else if (strcmp([num objCType], @encode(double)) == 0) {
return Variant((float)[num doubleValue]); return Variant((float)[num doubleValue]);
} }
} else if ([object isKindOfClass:[NSDate class]]) { } else if ([object isKindOfClass:[NSDate class]]) {
@ -145,7 +145,7 @@ Variant nsobject_to_variant(NSObject* object) {
} }
} }
NSObject* variant_to_nsobject(Variant v) { NSObject *variant_to_nsobject(Variant v) {
if (v.get_type() == Variant::STRING) { if (v.get_type() == Variant::STRING) {
return [[[NSString alloc] initWithUTF8String:((String)v).utf8().get_data()] autorelease]; return [[[NSString alloc] initWithUTF8String:((String)v).utf8().get_data()] autorelease];
} else if (v.get_type() == Variant::REAL) { } else if (v.get_type() == Variant::REAL) {
@ -155,12 +155,12 @@ NSObject* variant_to_nsobject(Variant v) {
} else if (v.get_type() == Variant::BOOL) { } else if (v.get_type() == Variant::BOOL) {
return [NSNumber numberWithBool:BOOL((bool)v)]; return [NSNumber numberWithBool:BOOL((bool)v)];
} else if (v.get_type() == Variant::DICTIONARY) { } else if (v.get_type() == Variant::DICTIONARY) {
NSMutableDictionary* result = [[[NSMutableDictionary alloc] init] autorelease]; NSMutableDictionary *result = [[[NSMutableDictionary alloc] init] autorelease];
Dictionary dic = v; Dictionary dic = v;
Array keys = dic.keys(); Array keys = dic.keys();
for (unsigned int i = 0; i < keys.size(); ++i) { for (unsigned int i = 0; i < keys.size(); ++i) {
NSString* key = [[[NSString alloc] initWithUTF8String:((String)(keys[i])).utf8().get_data()] autorelease]; NSString *key = [[[NSString alloc] initWithUTF8String:((String)(keys[i])).utf8().get_data()] autorelease];
NSObject* value = variant_to_nsobject(dic[keys[i]]); NSObject *value = variant_to_nsobject(dic[keys[i]]);
if (key == NULL || value == NULL) { if (key == NULL || value == NULL) {
return NULL; return NULL;
@ -170,10 +170,10 @@ NSObject* variant_to_nsobject(Variant v) {
} }
return result; return result;
} else if (v.get_type() == Variant::ARRAY) { } else if (v.get_type() == Variant::ARRAY) {
NSMutableArray* result = [[[NSMutableArray alloc] init] autorelease]; NSMutableArray *result = [[[NSMutableArray alloc] init] autorelease];
Array arr = v; Array arr = v;
for (unsigned int i = 0; i < arr.size(); ++i) { for (unsigned int i = 0; i < arr.size(); ++i) {
NSObject* value = variant_to_nsobject(arr[i]); NSObject *value = variant_to_nsobject(arr[i]);
if (value == NULL) { if (value == NULL) {
//trying to add something unsupported to the array. cancel the whole array //trying to add something unsupported to the array. cancel the whole array
return NULL; return NULL;
@ -184,17 +184,16 @@ NSObject* variant_to_nsobject(Variant v) {
} else if (v.get_type() == Variant::POOL_BYTE_ARRAY) { } else if (v.get_type() == Variant::POOL_BYTE_ARRAY) {
PoolByteArray arr = v; PoolByteArray arr = v;
PoolByteArray::Read r = arr.read(); PoolByteArray::Read r = arr.read();
NSData* result = [NSData dataWithBytes:r.ptr() length:arr.size()]; NSData *result = [NSData dataWithBytes:r.ptr() length:arr.size()];
return result; return result;
} }
WARN_PRINT(String("Could not add unsupported type to iCloud: '" + Variant::get_type_name(v.get_type())+"'").utf8().get_data()); WARN_PRINT(String("Could not add unsupported type to iCloud: '" + Variant::get_type_name(v.get_type()) + "'").utf8().get_data());
return NULL; return NULL;
} }
Error ICloud::remove_key(Variant p_param) { Error ICloud::remove_key(Variant p_param) {
String param = p_param; String param = p_param;
NSString* key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease]; NSString *key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease];
NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore]; NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
@ -217,13 +216,13 @@ Variant ICloud::set_key_values(Variant p_params) {
String variant_key = keys[i]; String variant_key = keys[i];
Variant variant_value = params[variant_key]; Variant variant_value = params[variant_key];
NSString* key = [[[NSString alloc] initWithUTF8String:variant_key.utf8().get_data()] autorelease]; NSString *key = [[[NSString alloc] initWithUTF8String:variant_key.utf8().get_data()] autorelease];
if (key == NULL) { if (key == NULL) {
error_keys.push_back(variant_key); error_keys.push_back(variant_key);
continue; continue;
} }
NSObject* value = variant_to_nsobject(variant_value); NSObject *value = variant_to_nsobject(variant_value);
if (value == NULL) { if (value == NULL) {
error_keys.push_back(variant_key); error_keys.push_back(variant_key);
@ -240,7 +239,7 @@ Variant ICloud::set_key_values(Variant p_params) {
Variant ICloud::get_key_value(Variant p_param) { Variant ICloud::get_key_value(Variant p_param) {
String param = p_param; String param = p_param;
NSString* key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease]; NSString *key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease];
NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore]; NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
if (![[store dictionaryRepresentation] objectForKey:key]) { if (![[store dictionaryRepresentation] objectForKey:key]) {
@ -255,16 +254,16 @@ Variant ICloud::get_key_value(Variant p_param) {
Variant ICloud::get_all_key_values() { Variant ICloud::get_all_key_values() {
Dictionary result; Dictionary result;
NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore]; NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
NSDictionary* store_dictionary = [store dictionaryRepresentation]; NSDictionary *store_dictionary = [store dictionaryRepresentation];
NSArray* keys = [store_dictionary allKeys]; NSArray *keys = [store_dictionary allKeys];
int count = [keys count]; int count = [keys count];
for (int i=0; i < count; ++i) { for (int i = 0; i < count; ++i) {
NSString* k = [ keys objectAtIndex:i]; NSString *k = [keys objectAtIndex:i];
NSObject* v = [store_dictionary objectForKey:k]; NSObject *v = [store_dictionary objectForKey:k];
const char* str = [k UTF8String]; const char *str = [k UTF8String];
if (str != NULL) { if (str != NULL) {
result[String::utf8(str)] = nsobject_to_variant(v); result[String::utf8(str)] = nsobject_to_variant(v);
} }
@ -302,62 +301,56 @@ ICloud::ICloud() {
instance = this; instance = this;
//connected = false; //connected = false;
[ [[NSNotificationCenter defaultCenter]
//[NSNotificationCenter defaultCenter] addObserverForName: @"notify" addObserverForName:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
[NSNotificationCenter defaultCenter] addObserverForName: NSUbiquitousKeyValueStoreDidChangeExternallyNotification object:[NSUbiquitousKeyValueStore defaultStore]
object: [NSUbiquitousKeyValueStore defaultStore] queue:nil
queue: nil usingBlock:^(NSNotification *notification) {
usingBlock: ^ (NSNotification * notification) { NSDictionary *userInfo = [notification userInfo];
NSDictionary* userInfo = [notification userInfo]; NSInteger change = [[userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey] integerValue];
NSInteger change = [[userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey] integerValue];
Dictionary ret; Dictionary ret;
ret["type"] = "key_value_changed"; ret["type"] = "key_value_changed";
//PoolStringArray result_keys; //PoolStringArray result_keys;
//Array result_values; //Array result_values;
Dictionary keyValues; Dictionary keyValues;
String reason = ""; String reason = "";
if (change == NSUbiquitousKeyValueStoreServerChange) { if (change == NSUbiquitousKeyValueStoreServerChange) {
reason = "server"; reason = "server";
} else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) { } else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) {
reason = "initial_sync"; reason = "initial_sync";
} else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) { } else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) {
reason = "quota_violation"; reason = "quota_violation";
} else if (change == NSUbiquitousKeyValueStoreAccountChange) { } else if (change == NSUbiquitousKeyValueStoreAccountChange) {
reason = "account"; reason = "account";
} }
ret["reason"] = reason; ret["reason"] = reason;
NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore];
NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore]; NSArray *keys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey];
for (NSString *key in keys) {
const char *str = [key UTF8String];
if (str == NULL) {
continue;
}
NSArray * keys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey]; NSObject *object = [store objectForKey:key];
for (NSString* key in keys) {
const char* str = [key UTF8String];
if (str == NULL) {
continue;
}
NSObject* object = [store objectForKey:key]; //figure out what kind of object it is
Variant value = nsobject_to_variant(object);
//figure out what kind of object it is keyValues[String::utf8(str)] = value;
Variant value = nsobject_to_variant(object); }
keyValues[String::utf8(str)] = value; ret["changed_values"] = keyValues;
} pending_events.push_back(ret);
}];
ret["changed_values"] = keyValues;
pending_events.push_back(ret);
}
];
} }
ICloud::~ICloud(){};
ICloud::~ICloud() {
};
#endif #endif

View file

@ -29,22 +29,22 @@
/*************************************************************************/ /*************************************************************************/
#ifdef STOREKIT_ENABLED #ifdef STOREKIT_ENABLED
#include "in_app_store.h"
#ifdef MODULE_FUSEBOXX_ENABLED #ifdef MODULE_FUSEBOXX_ENABLED
#import "modules/fuseboxx/ios/FuseSDK.h" #import "modules/fuseboxx/ios/FuseSDK.h"
#endif #endif
#include "in_app_store.h"
extern "C" { extern "C" {
#import <StoreKit/StoreKit.h>
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>
}; };
bool auto_finish_transactions = true; bool auto_finish_transactions = true;
NSMutableDictionary* pending_transactions = [NSMutableDictionary dictionary]; NSMutableDictionary *pending_transactions = [NSMutableDictionary dictionary];
@interface SKProduct (LocalizedPrice) @interface SKProduct (LocalizedPrice)
@property (nonatomic, readonly) NSString *localizedPrice; @property(nonatomic, readonly) NSString *localizedPrice;
@end @end
//----------------------------------// //----------------------------------//
@ -62,30 +62,28 @@ NSMutableDictionary* pending_transactions = [NSMutableDictionary dictionary];
} }
@end @end
InAppStore *InAppStore::instance = NULL;
InAppStore* InAppStore::instance = NULL;
void InAppStore::_bind_methods() { void InAppStore::_bind_methods() {
ClassDB::bind_method(D_METHOD("request_product_info"),&InAppStore::request_product_info); ClassDB::bind_method(D_METHOD("request_product_info"), &InAppStore::request_product_info);
ClassDB::bind_method(D_METHOD("purchase"),&InAppStore::purchase); ClassDB::bind_method(D_METHOD("purchase"), &InAppStore::purchase);
ClassDB::bind_method(D_METHOD("get_pending_event_count"),&InAppStore::get_pending_event_count); ClassDB::bind_method(D_METHOD("get_pending_event_count"), &InAppStore::get_pending_event_count);
ClassDB::bind_method(D_METHOD("pop_pending_event"),&InAppStore::pop_pending_event); ClassDB::bind_method(D_METHOD("pop_pending_event"), &InAppStore::pop_pending_event);
ClassDB::bind_method(D_METHOD("finish_transaction"),&InAppStore::finish_transaction); ClassDB::bind_method(D_METHOD("finish_transaction"), &InAppStore::finish_transaction);
ClassDB::bind_method(D_METHOD("set_auto_finish_transaction"),&InAppStore::set_auto_finish_transaction); ClassDB::bind_method(D_METHOD("set_auto_finish_transaction"), &InAppStore::set_auto_finish_transaction);
}; };
@interface ProductsDelegate : NSObject<SKProductsRequestDelegate> { @interface ProductsDelegate : NSObject <SKProductsRequestDelegate> {
}; };
@end @end
@implementation ProductsDelegate @implementation ProductsDelegate
- (void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response { - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSArray* products = response.products; NSArray *products = response.products;
Dictionary ret; Dictionary ret;
ret["type"] = "product_info"; ret["type"] = "product_info";
ret["result"] = "ok"; ret["result"] = "ok";
@ -95,11 +93,11 @@ void InAppStore::_bind_methods() {
PoolStringArray ids; PoolStringArray ids;
PoolStringArray localized_prices; PoolStringArray localized_prices;
for (int i=0; i<[products count]; i++) { for (int i = 0; i < [products count]; i++) {
SKProduct* product = [products objectAtIndex:i]; SKProduct *product = [products objectAtIndex:i];
const char* str = [product.localizedTitle UTF8String]; const char *str = [product.localizedTitle UTF8String];
titles.push_back(String::utf8(str != NULL ? str : "")); titles.push_back(String::utf8(str != NULL ? str : ""));
str = [product.localizedDescription UTF8String]; str = [product.localizedDescription UTF8String];
@ -116,7 +114,7 @@ void InAppStore::_bind_methods() {
PoolStringArray invalid_ids; PoolStringArray invalid_ids;
for (NSString* ipid in response.invalidProductIdentifiers) { for (NSString *ipid in response.invalidProductIdentifiers) {
invalid_ids.push_back(String::utf8([ipid UTF8String])); invalid_ids.push_back(String::utf8([ipid UTF8String]));
}; };
@ -137,15 +135,15 @@ Error InAppStore::request_product_info(Variant p_params) {
PoolStringArray pids = params["product_ids"]; PoolStringArray pids = params["product_ids"];
printf("************ request product info! %i\n", pids.size()); printf("************ request product info! %i\n", pids.size());
NSMutableArray* array = [[[NSMutableArray alloc] initWithCapacity:pids.size()] autorelease]; NSMutableArray *array = [[[NSMutableArray alloc] initWithCapacity:pids.size()] autorelease];
for (int i=0; i<pids.size(); i++) { for (int i = 0; i < pids.size(); i++) {
printf("******** adding %ls to product list\n", pids[i].c_str()); printf("******** adding %ls to product list\n", pids[i].c_str());
NSString* pid = [[[NSString alloc] initWithUTF8String:pids[i].utf8().get_data()] autorelease]; NSString *pid = [[[NSString alloc] initWithUTF8String:pids[i].utf8().get_data()] autorelease];
[array addObject:pid]; [array addObject:pid];
}; };
NSSet* products = [[[NSSet alloc] initWithArray:array] autorelease]; NSSet *products = [[[NSSet alloc] initWithArray:array] autorelease];
SKProductsRequest* request = [[SKProductsRequest alloc] initWithProductIdentifiers:products]; SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:products];
ProductsDelegate *delegate = [[ProductsDelegate alloc] init]; ProductsDelegate *delegate = [[ProductsDelegate alloc] init];
@ -155,17 +153,16 @@ Error InAppStore::request_product_info(Variant p_params) {
return OK; return OK;
}; };
@interface TransObserver : NSObject<SKPaymentTransactionObserver> { @interface TransObserver : NSObject <SKPaymentTransactionObserver> {
}; };
@end @end
@implementation TransObserver @implementation TransObserver
- (void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray*) transactions { - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
printf("transactions updated!\n"); printf("transactions updated!\n");
for (SKPaymentTransaction* transaction in transactions) { for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) { switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased: { case SKPaymentTransactionStatePurchased: {
@ -179,10 +176,10 @@ Error InAppStore::request_product_info(Variant p_params) {
ret["product_id"] = pid; ret["product_id"] = pid;
ret["transaction_id"] = transactionId; ret["transaction_id"] = transactionId;
NSData* receipt = nil; NSData *receipt = nil;
int sdk_version = 6; int sdk_version = 6;
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){ if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
NSURL *receiptFileURL = nil; NSURL *receiptFileURL = nil;
NSBundle *bundle = [NSBundle mainBundle]; NSBundle *bundle = [NSBundle mainBundle];
@ -207,9 +204,9 @@ Error InAppStore::request_product_info(Variant p_params) {
receipt = transaction.transactionReceipt; receipt = transaction.transactionReceipt;
} }
NSString* receipt_to_send = nil; NSString *receipt_to_send = nil;
if (receipt != nil) { if (receipt != nil) {
receipt_to_send = [receipt description]; receipt_to_send = [receipt description];
} }
Dictionary receipt_ret; Dictionary receipt_ret;
receipt_ret["receipt"] = String::utf8(receipt_to_send != nil ? [receipt_to_send UTF8String] : ""); receipt_ret["receipt"] = String::utf8(receipt_to_send != nil ? [receipt_to_send UTF8String] : "");
@ -218,15 +215,15 @@ Error InAppStore::request_product_info(Variant p_params) {
InAppStore::get_singleton()->_post_event(ret); InAppStore::get_singleton()->_post_event(ret);
if (auto_finish_transactions){ if (auto_finish_transactions) {
[[SKPaymentQueue defaultQueue] finishTransaction:transaction]; [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
} else{ } else {
[pending_transactions setObject:transaction forKey:transaction.payment.productIdentifier]; [pending_transactions setObject:transaction forKey:transaction.payment.productIdentifier];
} }
#ifdef MODULE_FUSEBOXX_ENABLED #ifdef MODULE_FUSEBOXX_ENABLED
printf("Registering transaction on Fuseboxx!\n"); printf("Registering transaction on Fuseboxx!\n");
[FuseSDK registerInAppPurchase: transaction]; [FuseSDK registerInAppPurchase:transaction];
#endif #endif
}; break; }; break;
case SKPaymentTransactionStateFailed: { case SKPaymentTransactionStateFailed: {
@ -254,7 +251,6 @@ Error InAppStore::request_product_info(Variant p_params) {
@end @end
Error InAppStore::purchase(Variant p_params) { Error InAppStore::purchase(Variant p_params) {
ERR_FAIL_COND_V(![SKPaymentQueue canMakePayments], ERR_UNAVAILABLE); ERR_FAIL_COND_V(![SKPaymentQueue canMakePayments], ERR_UNAVAILABLE);
@ -267,14 +263,13 @@ Error InAppStore::purchase(Variant p_params) {
NSString *pid = [[[NSString alloc] initWithUTF8String:String(params["product_id"]).utf8().get_data()] autorelease]; NSString *pid = [[[NSString alloc] initWithUTF8String:String(params["product_id"]).utf8().get_data()] autorelease];
SKPayment *payment = [SKPayment paymentWithProductIdentifier:pid]; SKPayment *payment = [SKPayment paymentWithProductIdentifier:pid];
SKPaymentQueue* defq = [SKPaymentQueue defaultQueue]; SKPaymentQueue *defq = [SKPaymentQueue defaultQueue];
[defq addPayment:payment]; [defq addPayment:payment];
printf("purchase sent!\n"); printf("purchase sent!\n");
return OK; return OK;
}; };
int InAppStore::get_pending_event_count() { int InAppStore::get_pending_event_count() {
return pending_events.size(); return pending_events.size();
}; };
@ -294,13 +289,13 @@ void InAppStore::_post_event(Variant p_event) {
void InAppStore::_record_purchase(String product_id) { void InAppStore::_record_purchase(String product_id) {
String skey = "purchased/"+product_id; String skey = "purchased/" + product_id;
NSString* key = [[[NSString alloc] initWithUTF8String:skey.utf8().get_data()] autorelease]; NSString *key = [[[NSString alloc] initWithUTF8String:skey.utf8().get_data()] autorelease];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:key]; [[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize]; [[NSUserDefaults standardUserDefaults] synchronize];
}; };
InAppStore* InAppStore::get_singleton() { InAppStore *InAppStore::get_singleton() {
return instance; return instance;
}; };
@ -310,27 +305,24 @@ InAppStore::InAppStore() {
instance = this; instance = this;
auto_finish_transactions = false; auto_finish_transactions = false;
TransObserver* observer = [[TransObserver alloc] init]; TransObserver *observer = [[TransObserver alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:observer]; [[SKPaymentQueue defaultQueue] addTransactionObserver:observer];
//pending_transactions = [NSMutableDictionary dictionary]; //pending_transactions = [NSMutableDictionary dictionary];
}; };
void InAppStore::finish_transaction(String product_id){ void InAppStore::finish_transaction(String product_id) {
NSString* prod_id = [NSString stringWithCString:product_id.utf8().get_data() encoding:NSUTF8StringEncoding]; NSString *prod_id = [NSString stringWithCString:product_id.utf8().get_data() encoding:NSUTF8StringEncoding];
if ([pending_transactions objectForKey:prod_id]){ if ([pending_transactions objectForKey:prod_id]) {
[[SKPaymentQueue defaultQueue] finishTransaction:[pending_transactions objectForKey:prod_id]]; [[SKPaymentQueue defaultQueue] finishTransaction:[pending_transactions objectForKey:prod_id]];
[pending_transactions removeObjectForKey:prod_id]; [pending_transactions removeObjectForKey:prod_id];
} }
}; };
void InAppStore::set_auto_finish_transaction(bool b){ void InAppStore::set_auto_finish_transaction(bool b) {
auto_finish_transactions = b; auto_finish_transactions = b;
} }
InAppStore::~InAppStore() { InAppStore::~InAppStore(){};
};
#endif #endif

View file

@ -33,7 +33,7 @@
void iOS::_bind_methods() { void iOS::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_rate_url","app_id"), &iOS::get_rate_url); ClassDB::bind_method(D_METHOD("get_rate_url", "app_id"), &iOS::get_rate_url);
}; };
String iOS::get_rate_url(int p_app_id) const { String iOS::get_rate_url(int p_app_id) const {
@ -47,7 +47,7 @@ String iOS::get_rate_url(int p_app_id) const {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 && [[[UIDevice currentDevice] systemVersion] floatValue] < 7.1) { if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0 && [[[UIDevice currentDevice] systemVersion] floatValue] < 7.1) {
// iOS 7 needs a different templateReviewURL @see https://github.com/arashpayan/appirater/issues/131 // iOS 7 needs a different templateReviewURL @see https://github.com/arashpayan/appirater/issues/131
ret = templ_iOS7; ret = templ_iOS7;
} else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) { } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
// iOS 8 needs a different templateReviewURL also @see https://github.com/arashpayan/appirater/issues/182 // iOS 8 needs a different templateReviewURL also @see https://github.com/arashpayan/appirater/issues/182
ret = templ_iOS8; ret = templ_iOS8;
} }
@ -59,4 +59,4 @@ String iOS::get_rate_url(int p_app_id) const {
return ret; return ret;
}; };
iOS::iOS() {}; iOS::iOS(){};

View file

@ -27,12 +27,13 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/ /*************************************************************************/
#import <UIKit/UIKit.h>
#import "app_delegate.h" #import "app_delegate.h"
#import <UIKit/UIKit.h>
#include <stdio.h> #include <stdio.h>
int gargc; int gargc;
char** gargv; char **gargv;
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
printf("*********** main.m\n"); printf("*********** main.m\n");
@ -40,11 +41,10 @@ int main(int argc, char *argv[]) {
gargv = argv; gargv = argv;
NSAutoreleasePool *pool = [NSAutoreleasePool new]; NSAutoreleasePool *pool = [NSAutoreleasePool new];
AppDelegate* app = [AppDelegate alloc]; AppDelegate *app = [AppDelegate alloc];
printf("running app main\n"); printf("running app main\n");
UIApplicationMain(argc, argv, nil, @"AppDelegate"); UIApplicationMain(argc, argv, nil, @"AppDelegate");
printf("main done, pool release\n"); printf("main done, pool release\n");
[pool release]; [pool release];
return 0; return 0;
} }

View file

@ -33,45 +33,44 @@
extern "C" { extern "C" {
int add_path(int, char**); int add_path(int, char **);
int add_cmdline(int, char**); int add_cmdline(int, char **);
int add_path(int p_argc, char** p_args) { int add_path(int p_argc, char **p_args) {
NSString* str = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_path"];
if (!str)
return p_argc;
p_args[p_argc++] = "-path";
[str retain]; // memory leak lol (maybe make it static here and delete it in ViewController destructor? @todo
p_args[p_argc++] = (char*)[str cString];
p_args[p_argc] = NULL;
NSString *str = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_path"];
if (!str)
return p_argc; return p_argc;
};
int add_cmdline(int p_argc, char** p_args) { p_args[p_argc++] = "-path";
[str retain]; // memory leak lol (maybe make it static here and delete it in ViewController destructor? @todo
NSArray* arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_cmdline"]; p_args[p_argc++] = (char *)[str cString];
if (!arr) p_args[p_argc] = NULL;
return p_argc;
for (int i=0; i < [arr count]; i++) {
NSString* str = [arr objectAtIndex:i];
if (!str)
continue;
[str retain]; // @todo delete these at some point
p_args[p_argc++] = (char*)[str cString];
};
p_args[p_argc] = NULL;
return p_argc;
};
return p_argc;
}; };
int add_cmdline(int p_argc, char **p_args) {
NSArray *arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_cmdline"];
if (!arr)
return p_argc;
for (int i = 0; i < [arr count]; i++) {
NSString *str = [arr objectAtIndex:i];
if (!str)
continue;
[str retain]; // @todo delete these at some point
p_args[p_argc++] = (char *)[str cString];
};
p_args[p_argc] = NULL;
return p_argc;
};
}; // extern "C"
@interface ViewController () @interface ViewController ()
@end @end
@ -85,11 +84,11 @@ extern "C" {
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)p_orientation { - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)p_orientation {
if (/*OSIPhone::get_singleton() == NULL*/TRUE) { if (/*OSIPhone::get_singleton() == NULL*/ TRUE) {
printf("checking on info.plist\n"); printf("checking on info.plist\n");
NSArray* arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"]; NSArray *arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"];
switch(p_orientation) { switch (p_orientation) {
case UIInterfaceOrientationLandscapeLeft: case UIInterfaceOrientationLandscapeLeft:
return [arr indexOfObject:@"UIInterfaceOrientationLandscapeLeft"] != NSNotFound ? YES : NO; return [arr indexOfObject:@"UIInterfaceOrientationLandscapeLeft"] != NSNotFound ? YES : NO;
@ -109,22 +108,22 @@ extern "C" {
}; };
uint8_t supported = OSIPhone::get_singleton()->get_orientations(); uint8_t supported = OSIPhone::get_singleton()->get_orientations();
switch(p_orientation) { switch (p_orientation) {
case UIInterfaceOrientationLandscapeLeft: case UIInterfaceOrientationLandscapeLeft:
return supported & (1<<OSIPhone::LandscapeLeft) ? YES : NO; return supported & (1 << OSIPhone::LandscapeLeft) ? YES : NO;
case UIInterfaceOrientationLandscapeRight: case UIInterfaceOrientationLandscapeRight:
return supported & (1<<OSIPhone::LandscapeRight) ? YES : NO; return supported & (1 << OSIPhone::LandscapeRight) ? YES : NO;
case UIInterfaceOrientationPortrait: case UIInterfaceOrientationPortrait:
return supported & (1<<OSIPhone::PortraitDown) ? YES : NO; return supported & (1 << OSIPhone::PortraitDown) ? YES : NO;
case UIInterfaceOrientationPortraitUpsideDown: case UIInterfaceOrientationPortraitUpsideDown:
return supported & (1<<OSIPhone::PortraitUp) ? YES : NO; return supported & (1 << OSIPhone::PortraitUp) ? YES : NO;
default: default:
return NO; return NO;
} }
}; };
@ -133,7 +132,7 @@ extern "C" {
} }
#ifdef GAME_CENTER_ENABLED #ifdef GAME_CENTER_ENABLED
- (void) gameCenterViewControllerDidFinish:(GKGameCenterViewController*) gameCenterViewController { - (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController {
//[gameCenterViewController dismissViewControllerAnimated:YES completion:^{GameCenter::get_singleton()->game_center_closed();}];//version for signaling when overlay is completely gone //[gameCenterViewController dismissViewControllerAnimated:YES completion:^{GameCenter::get_singleton()->game_center_closed();}];//version for signaling when overlay is completely gone
GameCenter::get_singleton()->game_center_closed(); GameCenter::get_singleton()->game_center_closed();
[gameCenterViewController dismissViewControllerAnimated:YES completion:nil]; [gameCenterViewController dismissViewControllerAnimated:YES completion:nil];

View file

@ -35,17 +35,14 @@
#include <Foundation/NSString.h> #include <Foundation/NSString.h>
String DirAccessOSX::fix_unicode_name(const char *p_name) const {
String DirAccessOSX::fix_unicode_name(const char* p_name) const {
String fname; String fname;
NSString* nsstr = [[NSString stringWithUTF8String: p_name] precomposedStringWithCanonicalMapping]; NSString *nsstr = [[NSString stringWithUTF8String:p_name] precomposedStringWithCanonicalMapping];
fname.parse_utf8([nsstr UTF8String]); fname.parse_utf8([nsstr UTF8String]);
return fname; return fname;
} }
#endif //posix_enabled #endif //posix_enabled

View file

@ -27,67 +27,62 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/ /*************************************************************************/
#include "os_osx.h"
#include "main/main.h" #include "main/main.h"
#include "os_osx.h"
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
//#define main godot_main int main(int argc, char **argv) {
int main(int argc, char** argv) {
int first_arg = 1; int first_arg = 1;
const char* dbg_arg = "-NSDocumentRevisionsDebugMode"; const char *dbg_arg = "-NSDocumentRevisionsDebugMode";
printf("arguments\n"); printf("arguments\n");
for (int i=0; i<argc; i++) { for (int i = 0; i < argc; i++) {
if (strcmp(dbg_arg, argv[i]) == 0) if (strcmp(dbg_arg, argv[i]) == 0)
first_arg = i+2; first_arg = i + 2;
printf("%i: %s\n", i, argv[i]); printf("%i: %s\n", i, argv[i]);
}; };
if (argc >= 1 && argv[0][0] == '/') { if (argc >= 1 && argv[0][0] == '/') {
//potentially launched from finder //potentially launched from finder
int len = strlen(argv[0]); int len = strlen(argv[0]);
while (len--) { while (len--) {
if (argv[0][len] == '/') break; if (argv[0][len] == '/') break;
} }
if (len>=0) { if (len >= 0) {
char *path = (char *)malloc(len+1); char *path = (char *)malloc(len + 1);
memcpy(path, argv[0], len); memcpy(path, argv[0], len);
path[len]=0; path[len] = 0;
char *pathinfo = (char*)malloc(strlen(path)+strlen("/../Info.plist")+1); char *pathinfo = (char *)malloc(strlen(path) + strlen("/../Info.plist") + 1);
//in real code you would check for errors in malloc here //in real code you would check for errors in malloc here
strcpy(pathinfo, path); strcpy(pathinfo, path);
strcat(pathinfo, "/../Info.plist"); strcat(pathinfo, "/../Info.plist");
FILE*f=fopen(pathinfo,"rb"); FILE *f = fopen(pathinfo, "rb");
if (f) { if (f) {
//running from app bundle, as Info.plist was found //running from app bundle, as Info.plist was found
fclose(f); fclose(f);
chdir(path); chdir(path);
chdir("../Resources"); //data.pck, or just the files are here chdir("../Resources"); //data.pck, or just the files are here
} }
free(path); free(path);
free(pathinfo); free(pathinfo);
} }
} }
OS_OSX os; OS_OSX os;
Error err = Main::setup(argv[0], argc - first_arg, &argv[first_arg]);
Error err = Main::setup(argv[0], argc-first_arg,&argv[first_arg]); if (err != OK)
if (err!=OK)
return 255; return 255;
if (Main::start()) if (Main::start())
os.run(); // it is actually the OS that decides how to run os.run(); // it is actually the OS that decides how to run
Main::cleanup(); Main::cleanup();
return 0; return 0;

View file

@ -27,14 +27,15 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/ /*************************************************************************/
#include "godot_osx.h"
#include <sys/param.h> /* for MAXPATHLEN */ #include <sys/param.h> /* for MAXPATHLEN */
#include <unistd.h> #include <unistd.h>
#include "godot_osx.h"
/* For some reaon, Apple removed setAppleMenu from the headers in 10.4, /* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
but the method still is there and works. To avoid warnings, we declare but the method still is there and works. To avoid warnings, we declare
it ourselves here. */ it ourselves here. */
@interface NSApplication() @interface NSApplication ()
- (void)setAppleMenu:(NSMenu *)menu; - (void)setAppleMenu:(NSMenu *)menu;
@end @end
@ -49,7 +50,7 @@ static NSString *getApplicationName(void) {
/* Determine the application name */ /* Determine the application name */
dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
if (dict) if (dict)
appName = [dict objectForKey: @"CFBundleName"]; appName = [dict objectForKey:@"CFBundleName"];
if (![appName length]) if (![appName length])
appName = [[NSProcessInfo processInfo] processName]; appName = [[NSProcessInfo processInfo] processName];
@ -80,7 +81,7 @@ static void setApplicationMenu(void) {
[appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask | NSCommandKeyMask)];
[appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
@ -89,7 +90,6 @@ static void setApplicationMenu(void) {
title = [@"Quit " stringByAppendingString:appName]; title = [@"Quit " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
/* Put menu into the menubar */ /* Put menu into the menubar */
menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
[menuItem setSubmenu:appleMenu]; [menuItem setSubmenu:appleMenu];
@ -105,9 +105,9 @@ static void setApplicationMenu(void) {
/* Create a window menu */ /* Create a window menu */
static void setupWindowMenu(void) { static void setupWindowMenu(void) {
NSMenu *windowMenu; NSMenu *windowMenu;
NSMenuItem *windowMenuItem; NSMenuItem *windowMenuItem;
NSMenuItem *menuItem; NSMenuItem *menuItem;
windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
@ -130,9 +130,9 @@ static void setupWindowMenu(void) {
} }
/* Replacement for NSApplicationMain */ /* Replacement for NSApplicationMain */
static void CustomApplicationMain (int argc, char **argv) { static void CustomApplicationMain(int argc, char **argv) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
GodotMain *main; GodotMain *main;
/* Ensure the application object is initialised */ /* Ensure the application object is initialised */
[NSApplication sharedApplication]; [NSApplication sharedApplication];
@ -152,10 +152,10 @@ static void CustomApplicationMain (int argc, char **argv) {
[pool release]; [pool release];
} }
extern int godot_main(int argc, char** argv); extern int godot_main(int argc, char **argv);
/* Called when the internal event loop has just started running */ /* Called when the internal event loop has just started running */
- (void) applicationDidFinishLaunching: (NSNotification *) note { - (void)applicationDidFinishLaunching:(NSNotification *)note {
int status; int status;
/* Hand off to main application code */ /* Hand off to main application code */
@ -168,15 +168,14 @@ extern int godot_main(int argc, char** argv);
@end @end
#ifdef main #ifdef main
# undef main #undef main
#endif #endif
int main(int argc, char **argv) {
int main (int argc, char **argv) {
/* Copy the arguments into a global variable */ /* Copy the arguments into a global variable */
/* This is passed if we are launched by double-clicking */ /* This is passed if we are launched by double-clicking */
if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { if (argc >= 2 && strncmp(argv[1], "-psn", 4) == 0) {
global_argv = (char **) malloc(sizeof (char *) * 2); global_argv = (char **)malloc(sizeof(char *) * 2);
global_argv[0] = argv[0]; global_argv[0] = argv[0];
global_argv[1] = NULL; global_argv[1] = NULL;
global_argc = 1; global_argc = 1;
@ -184,14 +183,14 @@ int main (int argc, char **argv) {
// chdir to binary's dir when launched from finder // chdir to binary's dir when launched from finder
int len = strlen(global_argv[0]); int len = strlen(global_argv[0]);
while (len--){ while (len--) {
if (global_argv[0][len] == '/') break; if (global_argv[0][len] == '/') break;
} }
if (len>=0) { if (len >= 0) {
char *path = (char *)malloc(len+1); char *path = (char *)malloc(len + 1);
memcpy(path, global_argv[0], len); memcpy(path, global_argv[0], len);
path[len]=0; path[len] = 0;
printf("Path: %s\n", path); printf("Path: %s\n", path);
chdir(path); chdir(path);
} }
@ -199,12 +198,11 @@ int main (int argc, char **argv) {
} else { } else {
int i; int i;
global_argc = argc; global_argc = argc;
global_argv = (char **) malloc(sizeof (char *) * (argc+1)); global_argv = (char **)malloc(sizeof(char *) * (argc + 1));
for (i = 0; i <= argc; i++) for (i = 0; i <= argc; i++)
global_argv[i] = argv[i]; global_argv[i] = argv[i];
} }
CustomApplicationMain (argc, argv); CustomApplicationMain(argc, argv);
return 0; return 0;
} }

File diff suppressed because it is too large Load diff