From 33ea9fc4a73e4f80b40878d68eb2d0c595d1c322 Mon Sep 17 00:00:00 2001 From: BastiaanOlij Date: Sat, 8 Apr 2017 09:47:13 +1000 Subject: [PATCH] Spaces to tabs and layout adjustments on .mm files --- .gitattributes | 1 + platform/iphone/app_delegate.mm | 385 +++++---- platform/iphone/game_center.mm | 56 +- platform/iphone/gl_view.mm | 225 +++--- platform/iphone/icloud.mm | 99 +-- platform/iphone/in_app_store.mm | 163 ++-- platform/iphone/ios.mm | 9 +- platform/iphone/main.m | 3 +- platform/iphone/view_controller.mm | 107 ++- platform/osx/godot_main_osx.mm | 17 +- platform/osx/godot_osx.mm | 193 +++-- platform/osx/os_osx.mm | 1214 +++++++++++++--------------- 12 files changed, 1172 insertions(+), 1300 deletions(-) diff --git a/.gitattributes b/.gitattributes index 1df99d85bf..28940450d1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -5,5 +5,6 @@ drivers/* linguist-vendored *.cpp eol=lf *.h eol=lf +*.mm eol=lf *.py eol=lf *.hpp eol=lf diff --git a/platform/iphone/app_delegate.mm b/platform/iphone/app_delegate.mm index bd96ba8e2d..1e6e6beaf4 100644 --- a/platform/iphone/app_delegate.mm +++ b/platform/iphone/app_delegate.mm @@ -58,10 +58,10 @@ void _set_keep_screen_on(bool p_enabled); Error _shell_open(String p_uri) { NSString* url = [[NSString alloc] initWithUTF8String:p_uri.utf8().get_data()]; - if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]]) - return ERR_CANT_OPEN; + if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]]) + return ERR_CANT_OPEN; - printf("opening url %ls\n", p_uri.c_str()); + printf("opening url %ls\n", p_uri.c_str()); [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]]; [url release]; return OK; @@ -84,8 +84,7 @@ CMMotionManager *motionManager; bool motionInitialised; static ViewController* mainViewController = nil; -+ (ViewController*) getViewController -{ ++ (ViewController*) getViewController { return mainViewController; } @@ -93,157 +92,152 @@ static int frame_count = 0; - (void)drawView:(GLView*)view; { switch (frame_count) { + case 0: { + int backingWidth; + int backingHeight; + glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth); + glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight); - case 0: { - int backingWidth; - int backingHeight; - glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth); - glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight); + OS::VideoMode vm; + vm.fullscreen = true; + vm.width = backingWidth; + vm.height = backingHeight; + vm.resizable = false; + OS::get_singleton()->set_video_mode(vm); - - OS::VideoMode vm; - vm.fullscreen = true; - vm.width = backingWidth; - vm.height = backingHeight; - vm.resizable = false; - OS::get_singleton()->set_video_mode(vm); - - if (!OS::get_singleton()) { - exit(0); - }; - ++frame_count; - - NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString *documentsDirectory = [paths objectAtIndex:0]; - //NSString *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; - OSIPhone::get_singleton()->set_data_dir(String::utf8([documentsDirectory UTF8String])); - - NSString *locale_code = [[[NSLocale preferredLanguages] objectAtIndex:0] substringToIndex:2]; - OSIPhone::get_singleton()->set_locale(String::utf8([locale_code UTF8String])); - - NSString* uuid; - if ([[UIDevice currentDevice]respondsToSelector:@selector(identifierForVendor)]) { - uuid = [UIDevice currentDevice].identifierForVendor.UUIDString; - }else{ - - // before iOS 6, so just generate an identifier and store it - uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"identiferForVendor"]; - if( !uuid ) { - CFUUIDRef cfuuid = CFUUIDCreate(NULL); - uuid = (__bridge_transfer NSString*)CFUUIDCreateString(NULL, cfuuid); - CFRelease(cfuuid); - [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"identifierForVendor"]; - } - } - - OSIPhone::get_singleton()->set_unique_ID(String::utf8([uuid UTF8String])); - - }; break; -/* - case 1: { - ++frame_count; - } break; -*/ - case 1: { - - Main::setup2(); - ++frame_count; - - // this might be necessary before here - NSDictionary* dict = [[NSBundle mainBundle] infoDictionary]; - for (NSString* key in dict) { - NSObject* value = [dict objectForKey:key]; - String ukey = String::utf8([key UTF8String]); - - // we need a NSObject to Variant conversor - - if ([value isKindOfClass:[NSString class]]) { - NSString* str = (NSString*)value; - String uval = String::utf8([str UTF8String]); - - Globals::get_singleton()->set("Info.plist/"+ukey, uval); - - } else if ([value isKindOfClass:[NSNumber class]]) { - - NSNumber* n = (NSNumber*)value; - double dval = [n doubleValue]; - - Globals::get_singleton()->set("Info.plist/"+ukey, dval); + if (!OS::get_singleton()) { + exit(0); }; - // do stuff - } + ++frame_count; - } break; -/* - case 3: { - ++frame_count; - } break; -*/ - case 2: { + NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + //NSString *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; + OSIPhone::get_singleton()->set_data_dir(String::utf8([documentsDirectory UTF8String])); - Main::start(); - ++frame_count; + NSString *locale_code = [[[NSLocale preferredLanguages] objectAtIndex:0] substringToIndex:2]; + OSIPhone::get_singleton()->set_locale(String::utf8([locale_code UTF8String])); - }; break; // no fallthrough + NSString* uuid; + if ([[UIDevice currentDevice]respondsToSelector:@selector(identifierForVendor)]) { + uuid = [UIDevice currentDevice].identifierForVendor.UUIDString; + } else { - default: { - - if (OSIPhone::get_singleton()) { - if (motionInitialised) { - // 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: - // https://developer.apple.com/reference/coremotion/cmmotionmanager?language=objc - - // Apple splits our accelerometer date into a gravity and user movement component. We add them back together - CMAcceleration gravity = motionManager.deviceMotion.gravity; - CMAcceleration acceleration = motionManager.deviceMotion.userAcceleration; - - ///@TODO We don't seem to be getting data here, is my device broken or is this code incorrect? - CMMagneticField magnetic = motionManager.deviceMotion.magneticField.field; - - ///@TODO we can access rotationRate as a CMRotationRate variable (processed date) or CMGyroData (raw data), have to see what works best - CMRotationRate rotation = motionManager.deviceMotion.rotationRate; - - // Adjust for screen orientation. - // [[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 - - ///@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) - - switch ([[UIApplication sharedApplication] statusBarOrientation]) { - case UIDeviceOrientationLandscapeLeft: { - OSIPhone::get_singleton()->update_gravity(-gravity.y, gravity.x, gravity.z); - OSIPhone::get_singleton()->update_accelerometer(-(acceleration.y + gravity.y), (acceleration.x + gravity.x), acceleration.z + gravity.z); - OSIPhone::get_singleton()->update_magnetometer(-magnetic.y, magnetic.x, magnetic.z); - OSIPhone::get_singleton()->update_gyroscope(-rotation.y, rotation.x, rotation.z); - }; break; - case UIDeviceOrientationLandscapeRight: { - OSIPhone::get_singleton()->update_gravity(gravity.y, -gravity.x, gravity.z); - OSIPhone::get_singleton()->update_accelerometer((acceleration.y + gravity.y), -(acceleration.x + gravity.x), acceleration.z + gravity.z); - OSIPhone::get_singleton()->update_magnetometer(magnetic.y, -magnetic.x, magnetic.z); - OSIPhone::get_singleton()->update_gyroscope(rotation.y, -rotation.x, rotation.z); - }; break; - case UIDeviceOrientationPortraitUpsideDown: { - OSIPhone::get_singleton()->update_gravity(-gravity.x, gravity.y, gravity.z); - OSIPhone::get_singleton()->update_accelerometer(-(acceleration.x + gravity.x), (acceleration.y + gravity.y), acceleration.z + gravity.z); - OSIPhone::get_singleton()->update_magnetometer(-magnetic.x, magnetic.y, magnetic.z); - OSIPhone::get_singleton()->update_gyroscope(-rotation.x, rotation.y, rotation.z); - }; break; - default: { // assume portrait - OSIPhone::get_singleton()->update_gravity(gravity.x, gravity.y, gravity.z); - OSIPhone::get_singleton()->update_accelerometer(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z); - OSIPhone::get_singleton()->update_magnetometer(magnetic.x, magnetic.y, magnetic.z); - OSIPhone::get_singleton()->update_gyroscope(rotation.x, rotation.y, rotation.z); - }; break; - }; + // before iOS 6, so just generate an identifier and store it + uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"identiferForVendor"]; + if( !uuid ) { + CFUUIDRef cfuuid = CFUUIDCreate(NULL); + uuid = (__bridge_transfer NSString*)CFUUIDCreateString(NULL, cfuuid); + CFRelease(cfuuid); + [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"identifierForVendor"]; + } } - bool quit_request = OSIPhone::get_singleton()->iterate(); + OSIPhone::get_singleton()->set_unique_ID(String::utf8([uuid UTF8String])); + + }; break; +/* + case 1: { + ++frame_count; + }; break; +*/ + case 1: { + + Main::setup2(); + ++frame_count; + + // this might be necessary before here + NSDictionary* dict = [[NSBundle mainBundle] infoDictionary]; + for (NSString* key in dict) { + NSObject* value = [dict objectForKey:key]; + String ukey = String::utf8([key UTF8String]); + + // we need a NSObject to Variant conversor + + if ([value isKindOfClass:[NSString class]]) { + NSString* str = (NSString*)value; + String uval = String::utf8([str UTF8String]); + + Globals::get_singleton()->set("Info.plist/"+ukey, uval); + + } else if ([value isKindOfClass:[NSNumber class]]) { + + NSNumber* n = (NSNumber*)value; + double dval = [n doubleValue]; + + Globals::get_singleton()->set("Info.plist/"+ukey, dval); + }; + // do stuff + } + + }; break; +/* + case 3: { + ++frame_count; + } break; +*/ + case 2: { + + Main::start(); + ++frame_count; + + }; break; // no fallthrough + + default: { + if (OSIPhone::get_singleton()) { + if (motionInitialised) { + // 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: + // https://developer.apple.com/reference/coremotion/cmmotionmanager?language=objc + + // Apple splits our accelerometer date into a gravity and user movement component. We add them back together + CMAcceleration gravity = motionManager.deviceMotion.gravity; + CMAcceleration acceleration = motionManager.deviceMotion.userAcceleration; + + ///@TODO We don't seem to be getting data here, is my device broken or is this code incorrect? + CMMagneticField magnetic = motionManager.deviceMotion.magneticField.field; + + ///@TODO we can access rotationRate as a CMRotationRate variable (processed date) or CMGyroData (raw data), have to see what works best + CMRotationRate rotation = motionManager.deviceMotion.rotationRate; + + // Adjust for screen orientation. + // [[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 + + ///@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) + + switch ([[UIApplication sharedApplication] statusBarOrientation]) { + case UIDeviceOrientationLandscapeLeft: { + OSIPhone::get_singleton()->update_gravity(-gravity.y, gravity.x, gravity.z); + OSIPhone::get_singleton()->update_accelerometer(-(acceleration.y + gravity.y), (acceleration.x + gravity.x), acceleration.z + gravity.z); + OSIPhone::get_singleton()->update_magnetometer(-magnetic.y, magnetic.x, magnetic.z); + OSIPhone::get_singleton()->update_gyroscope(-rotation.y, rotation.x, rotation.z); + }; break; + case UIDeviceOrientationLandscapeRight: { + OSIPhone::get_singleton()->update_gravity(gravity.y, -gravity.x, gravity.z); + OSIPhone::get_singleton()->update_accelerometer((acceleration.y + gravity.y), -(acceleration.x + gravity.x), acceleration.z + gravity.z); + OSIPhone::get_singleton()->update_magnetometer(magnetic.y, -magnetic.x, magnetic.z); + OSIPhone::get_singleton()->update_gyroscope(rotation.y, -rotation.x, rotation.z); + }; break; + case UIDeviceOrientationPortraitUpsideDown: { + OSIPhone::get_singleton()->update_gravity(-gravity.x, gravity.y, gravity.z); + OSIPhone::get_singleton()->update_accelerometer(-(acceleration.x + gravity.x), (acceleration.y + gravity.y), acceleration.z + gravity.z); + OSIPhone::get_singleton()->update_magnetometer(-magnetic.x, magnetic.y, magnetic.z); + OSIPhone::get_singleton()->update_gyroscope(-rotation.x, rotation.y, rotation.z); + }; break; + default: { // assume portrait + OSIPhone::get_singleton()->update_gravity(gravity.x, gravity.y, gravity.z); + OSIPhone::get_singleton()->update_accelerometer(acceleration.x + gravity.x, acceleration.y + gravity.y, acceleration.z + gravity.z); + OSIPhone::get_singleton()->update_magnetometer(magnetic.x, magnetic.y, magnetic.z); + OSIPhone::get_singleton()->update_gyroscope(rotation.x, rotation.y, rotation.z); + }; break; + }; + } + + bool quit_request = OSIPhone::get_singleton()->iterate(); + }; }; - - }; - }; }; @@ -275,12 +269,12 @@ static int frame_count = 0; //glView.autoresizesSubviews = YES; //[glView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth]; - int backingWidth; - int backingHeight; - glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth); - glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight); + int backingWidth; + int backingHeight; + glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth); + glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight); - iphone_main(backingWidth, backingHeight, gargc, gargv); + iphone_main(backingWidth, backingHeight, gargc, gargv); view_controller = [[ViewController alloc] init]; view_controller.view = glView; @@ -296,13 +290,13 @@ static int frame_count = 0; [window makeKeyAndVisible]; if (!motionInitialised) { - motionManager = [[CMMotionManager alloc] init]; - if (motionManager.deviceMotionAvailable) { - motionManager.deviceMotionUpdateInterval = 1.0/70.0; - [motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical]; + motionManager = [[CMMotionManager alloc] init]; + if (motionManager.deviceMotionAvailable) { + motionManager.deviceMotionUpdateInterval = 1.0/70.0; + [motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical]; motionInitialised = YES; - }; - }; + }; + }; //OSIPhone::screen_width = rect.size.width - rect.origin.x; //OSIPhone::screen_height = rect.size.height - rect.origin.y; @@ -310,33 +304,29 @@ static int frame_count = 0; mainViewController = view_controller; #ifdef MODULE_GAME_ANALYTICS_ENABLED - printf("********************* didFinishLaunchingWithOptions\n"); - if(!Globals::get_singleton()->has("mobileapptracker/advertiser_id")) - { - return; - } - if(!Globals::get_singleton()->has("mobileapptracker/conversion_key")) - { - return; - } + printf("********************* didFinishLaunchingWithOptions\n"); + if (!Globals::get_singleton()->has("mobileapptracker/advertiser_id")) { + return; + } + if (!Globals::get_singleton()->has("mobileapptracker/conversion_key")) { + return; + } - String adid = GLOBAL_DEF("mobileapptracker/advertiser_id",""); - String convkey = GLOBAL_DEF("mobileapptracker/conversion_key",""); + String adid = GLOBAL_DEF("mobileapptracker/advertiser_id",""); + String convkey = GLOBAL_DEF("mobileapptracker/conversion_key",""); - NSString * advertiser_id = [NSString stringWithUTF8String:adid.utf8().get_data()]; - NSString * conversion_key = [NSString stringWithUTF8String:convkey.utf8().get_data()]; + NSString * advertiser_id = [NSString stringWithUTF8String:adid.utf8().get_data()]; + NSString * conversion_key = [NSString stringWithUTF8String:convkey.utf8().get_data()]; - // Account Configuration info - must be set - [MobileAppTracker initializeWithMATAdvertiserId:advertiser_id - MATConversionKey:conversion_key]; + // Account Configuration info - must be set + [MobileAppTracker initializeWithMATAdvertiserId:advertiser_id MATConversionKey:conversion_key]; - // Used to pass us the IFA, enables highly accurate 1-to-1 attribution. - // Required for many advertising networks. - [MobileAppTracker setAppleAdvertisingIdentifier:[[ASIdentifierManager sharedManager] advertisingIdentifier] - advertisingTrackingEnabled:[[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]]; + // Used to pass us the IFA, enables highly accurate 1-to-1 attribution. + // Required for many advertising networks. + [MobileAppTracker setAppleAdvertisingIdentifier:[[ASIdentifierManager sharedManager] advertisingIdentifier] + advertisingTrackingEnabled:[[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]]; #endif - }; - (void)applicationWillTerminate:(UIApplication*)application { @@ -344,53 +334,53 @@ static int frame_count = 0; printf("********************* will terminate\n"); if (motionInitialised) { - ///@TODO is this the right place to clean this up? - [motionManager stopDeviceMotionUpdates]; - [motionManager release]; - motionManager = nil; - motionInitialised = NO; - }; + ///@TODO is this the right place to clean this up? + [motionManager stopDeviceMotionUpdates]; + [motionManager release]; + motionManager = nil; + motionInitialised = NO; + }; iphone_finish(); }; -- (void)applicationDidEnterBackground:(UIApplication *)application -{ +- (void)applicationDidEnterBackground:(UIApplication *)application { printf("********************* did enter background\n"); ///@TODO maybe add pause motionManager? and where would we unpause it? if (OS::get_singleton()->get_main_loop()) OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT); + [view_controller.view stopAnimation]; + if (OS::get_singleton()->native_video_is_playing()) { OSIPhone::get_singleton()->native_video_focus_out(); }; } -- (void)applicationWillEnterForeground:(UIApplication *)application -{ +- (void)applicationWillEnterForeground:(UIApplication *)application { printf("********************* did enter foreground\n"); //OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN); [view_controller.view startAnimation]; } -- (void) applicationWillResignActive:(UIApplication *)application -{ +- (void) applicationWillResignActive:(UIApplication *)application { printf("********************* will resign active\n"); //OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT); [view_controller.view stopAnimation]; // FIXME: pause seems to be recommended elsewhere } -- (void) applicationDidBecomeActive:(UIApplication *)application -{ +- (void) applicationDidBecomeActive:(UIApplication *)application { printf("********************* did become active\n"); #ifdef MODULE_GAME_ANALYTICS_ENABLED - printf("********************* mobile app tracker found\n"); + printf("********************* mobile app tracker found\n"); [MobileAppTracker measureSession]; #endif if (OS::get_singleton()->get_main_loop()) OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN); + [view_controller.view startAnimation]; // FIXME: resume seems to be recommended elsewhere + if (OSIPhone::get_singleton()->native_video_is_playing()) { OSIPhone::get_singleton()->native_video_unpause(); }; @@ -409,9 +399,9 @@ static int frame_count = 0; #ifdef MODULE_PARSE_ENABLED NSLog(@"Handling application openURL"); return [[FBSDKApplicationDelegate sharedInstance] application:application - openURL:url - sourceApplication:sourceApplication - annotation:annotation]; + openURL:url + sourceApplication:sourceApplication + annotation:annotation]; #endif @@ -448,8 +438,7 @@ static int frame_count = 0; #endif } -- (void)dealloc -{ +- (void)dealloc { [window release]; [super dealloc]; } diff --git a/platform/iphone/game_center.mm b/platform/iphone/game_center.mm index aee5ceb211..3ef81a3f55 100644 --- a/platform/iphone/game_center.mm +++ b/platform/iphone/game_center.mm @@ -51,15 +51,15 @@ void GameCenter::_bind_methods() { ObjectTypeDB::bind_method(_MD("connect"),&GameCenter::connect); ObjectTypeDB::bind_method(_MD("is_connected"),&GameCenter::is_connected); - ObjectTypeDB::bind_method(_MD("post_score"),&GameCenter::post_score); - ObjectTypeDB::bind_method(_MD("award_achievement"),&GameCenter::award_achievement); - ObjectTypeDB::bind_method(_MD("reset_achievements"),&GameCenter::reset_achievements); - ObjectTypeDB::bind_method(_MD("request_achievements"),&GameCenter::request_achievements); - ObjectTypeDB::bind_method(_MD("request_achievement_descriptions"),&GameCenter::request_achievement_descriptions); - ObjectTypeDB::bind_method(_MD("show_game_center"),&GameCenter::show_game_center); + ObjectTypeDB::bind_method(_MD("post_score"), &GameCenter::post_score); + ObjectTypeDB::bind_method(_MD("award_achievement"), &GameCenter::award_achievement); + ObjectTypeDB::bind_method(_MD("reset_achievements"), &GameCenter::reset_achievements); + ObjectTypeDB::bind_method(_MD("request_achievements"), &GameCenter::request_achievements); + ObjectTypeDB::bind_method(_MD("request_achievement_descriptions"), &GameCenter::request_achievement_descriptions); + ObjectTypeDB::bind_method(_MD("show_game_center"), &GameCenter::show_game_center); - ObjectTypeDB::bind_method(_MD("get_pending_event_count"),&GameCenter::get_pending_event_count); - ObjectTypeDB::bind_method(_MD("pop_pending_event"),&GameCenter::pop_pending_event); + ObjectTypeDB::bind_method(_MD("get_pending_event_count"), &GameCenter::get_pending_event_count); + ObjectTypeDB::bind_method(_MD("pop_pending_event"), &GameCenter::pop_pending_event); }; @@ -77,27 +77,25 @@ Error GameCenter::connect() { ViewController *root_controller=(ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController; 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 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. player.authenticateHandler = (^(UIViewController *controller, NSError *error) { - if (controller) { - [root_controller presentViewController:controller animated:YES completion:nil]; - } - else { - Dictionary ret; - ret["type"] = "authentication"; - if (player.isAuthenticated) { - ret["result"] = "ok"; - GameCenter::get_singleton()->connected = true; - } else { - ret["result"] = "error"; - ret["error_code"] = error.code; - ret["error_description"] = [error.localizedDescription UTF8String]; - GameCenter::get_singleton()->connected = false; - }; - - pending_events.push_back(ret); - }; + if (controller) { + [root_controller presentViewController:controller animated:YES completion:nil]; + } else { + Dictionary ret; + ret["type"] = "authentication"; + if (player.isAuthenticated) { + ret["result"] = "ok"; + GameCenter::get_singleton()->connected = true; + } else { + ret["result"] = "error"; + ret["error_code"] = error.code; + ret["error_description"] = [error.localizedDescription UTF8String]; + GameCenter::get_singleton()->connected = false; + }; + pending_events.push_back(ret); + }; }); return OK; @@ -121,7 +119,6 @@ Error GameCenter::post_score(Variant p_score) { ERR_FAIL_COND_V([GKScore respondsToSelector:@selector(reportScores)], ERR_UNAVAILABLE); [GKScore reportScores:@[reporter] withCompletionHandler:^(NSError* error) { - Dictionary ret; ret["type"] = "post_score"; if (error == nil) { @@ -331,7 +328,8 @@ Error GameCenter::show_game_center(Variant p_params) { void GameCenter::game_center_closed() { Dictionary ret; - ret["type"] = "show_game_center"; + + ret["type"] = "show_game_center"; ret["result"] = "ok"; pending_events.push_back(ret); } diff --git a/platform/iphone/gl_view.mm b/platform/iphone/gl_view.mm index d8ed930157..dc18104fdb 100755 --- a/platform/iphone/gl_view.mm +++ b/platform/iphone/gl_view.mm @@ -90,9 +90,9 @@ bool _play_video(String p_path, float p_volume, String p_audio_track, String p_s [_instance.avPlayer addObserver:_instance forKeyPath:@"status" options:0 context:nil]; [[NSNotificationCenter defaultCenter] addObserver:_instance - selector:@selector(playerItemDidReachEnd:) - name:AVPlayerItemDidPlayToEndTimeNotification - object:[_instance.avPlayer currentItem]]; + selector:@selector(playerItemDidReachEnd:) + name:AVPlayerItemDidPlayToEndTimeNotification + object:[_instance.avPlayer currentItem]]; [_instance.avPlayer addObserver:_instance forKeyPath:@"rate" options:NSKeyValueObservingOptionNew context:0]; @@ -103,13 +103,11 @@ bool _play_video(String p_path, float p_volume, String p_audio_track, String p_s AVMediaSelectionGroup *audioGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic: AVMediaCharacteristicAudible]; NSMutableArray *allAudioParams = [NSMutableArray array]; - for (id track in audioGroup.options) - { + for (id track in audioGroup.options) { NSString* language = [[track locale] localeIdentifier]; NSLog(@"subtitle lang: %@", language); - if ([language isEqualToString:[NSString stringWithUTF8String:p_audio_track.utf8()]]) - { + if ([language isEqualToString:[NSString stringWithUTF8String:p_audio_track.utf8()]]) { AVMutableAudioMixInputParameters *audioInputParams = [AVMutableAudioMixInputParameters audioMixInputParameters]; [audioInputParams setVolume:p_volume atTime:kCMTimeZero]; [audioInputParams setTrackID:[track trackID]]; @@ -121,23 +119,21 @@ bool _play_video(String p_path, float p_volume, String p_audio_track, String p_s [_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup: audioGroup]; [_instance.avPlayer.currentItem setAudioMix:audioMix]; - break; - } + break; + } } AVMediaSelectionGroup *subtitlesGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic: AVMediaCharacteristicLegible]; 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]; NSLog(@"subtitle lang: %@", language); - if ([language isEqualToString:[NSString stringWithUTF8String:p_subtitle_track.utf8()]]) - { - [_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup: subtitlesGroup]; - break; - } + if ([language isEqualToString:[NSString stringWithUTF8String:p_subtitle_track.utf8()]]) { + [_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup: subtitlesGroup]; + break; + } } video_playing = true; @@ -237,7 +233,7 @@ static int get_first_id(UITouch* p_touch) { static void clear_touches() { - for (int i=0; i)delegate -{ +-(id)delegate { return delegate; } // Update the delegate, and if it needs a -setupView: call, set our internal flag so that it will be called. --(void)setDelegate:(id)d -{ +-(void)setDelegate:(id)d { delegate = d; delegateSetup = ![delegate respondsToSelector:@selector(setupView:)]; } @@ -305,8 +294,7 @@ static void clear_touches() { // This is the perfect opportunity to also update the framebuffer so that it is // the same size as our display area. --(void)layoutSubviews -{ +-(void)layoutSubviews { //printf("HERE\n"); [EAGLContext setCurrentContext:context]; [self destroyFramebuffer]; @@ -316,8 +304,7 @@ static void clear_touches() { } -- (BOOL)createFramebuffer -{ +- (BOOL)createFramebuffer { // Generate IDs for a framebuffer object and a color renderbuffer UIScreen* mainscr = [UIScreen mainScreen]; printf("******** screen size %i, %i\n", (int)mainscr.currentMode.size.width, (int)mainscr.currentMode.size.height); @@ -344,8 +331,7 @@ static void clear_touches() { glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight); 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)); return NO; } @@ -365,24 +351,22 @@ static void clear_touches() { } // Clean up any buffers we have allocated. -- (void)destroyFramebuffer -{ +- (void)destroyFramebuffer { glDeleteFramebuffersOES(1, &viewFramebuffer); viewFramebuffer = 0; glDeleteRenderbuffersOES(1, &viewRenderbuffer); viewRenderbuffer = 0; - if(depthRenderbuffer) - { + if(depthRenderbuffer) { glDeleteRenderbuffersOES(1, &depthRenderbuffer); depthRenderbuffer = 0; } } -- (void)startAnimation -{ +- (void)startAnimation { if (active) return; + active = TRUE; printf("start animation!\n"); if (useCADisplayLink) { @@ -396,59 +380,53 @@ static void clear_touches() { // Setup DisplayLink in main thread [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; - } - else { + } else { animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(drawView) userInfo:nil repeats:YES]; } - if (video_playing) - { + if (video_playing) { _unpause_video(); } } -- (void)stopAnimation -{ +- (void)stopAnimation { if (!active) return; + active = FALSE; printf("******** stop animation!\n"); if (useCADisplayLink) { [displayLink invalidate]; displayLink = nil; - } - else { + } else { [animationTimer invalidate]; animationTimer = nil; } clear_touches(); - if (video_playing) - { + if (video_playing) { // save position } } -- (void)setAnimationInterval:(NSTimeInterval)interval -{ +- (void)setAnimationInterval:(NSTimeInterval)interval { animationInterval = interval; - if ( (useCADisplayLink && displayLink) || ( !useCADisplayLink && animationTimer ) ) { + if ((useCADisplayLink && displayLink) || (!useCADisplayLink && animationTimer)) { [self stopAnimation]; [self startAnimation]; } } // Updates the OpenGL view when the timer fires -- (void)drawView -{ +- (void)drawView { if (useCADisplayLink) { // Pause the CADisplayLink to avoid recursion [displayLink setPaused: YES]; // Process all input events - while(CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource); + while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource); // We are good to go, resume the CADisplayLink [displayLink setPaused: NO]; @@ -463,8 +441,7 @@ static void clear_touches() { [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(!delegateSetup) - { + if(!delegateSetup) { [delegate setupView:self]; delegateSetup = YES; } @@ -483,8 +460,7 @@ static void clear_touches() { #endif } -- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event -{ +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSArray* tlist = [[event allTouches] allObjects]; for (unsigned int i=0; i< [tlist count]; i++) { @@ -501,8 +477,7 @@ static void clear_touches() { }; } -- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event -{ +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { NSArray* tlist = [[event allTouches] allObjects]; for (unsigned int i=0; i< [tlist count]; i++) { @@ -512,6 +487,7 @@ static void clear_touches() { UITouch* touch = [tlist objectAtIndex:i]; if (touch.phase != UITouchPhaseMoved) continue; + int tid = get_touch_id(touch); ERR_FAIL_COND(tid == -1); int first = get_first_id(touch); @@ -523,8 +499,7 @@ static void clear_touches() { } -- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event -{ +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { NSArray* tlist = [[event allTouches] allObjects]; for (unsigned int i=0; i< [tlist count]; i++) { @@ -533,6 +508,7 @@ static void clear_touches() { UITouch* touch = [tlist objectAtIndex:i]; if (touch.phase != UITouchPhaseEnded) continue; + int tid = get_touch_id(touch); ERR_FAIL_COND(tid == -1); int rem = remove_touch(touch); @@ -566,6 +542,7 @@ static void clear_touches() { - (void)deleteBackward { if (keyboard_text.length()) keyboard_text.erase(keyboard_text.length() - 1, 1); + OSIPhone::get_singleton()->key(KEY_BACKSPACE, true); }; @@ -590,12 +567,12 @@ static void clear_touches() { switch (routeChangeReason) { - case AVAudioSessionRouteChangeReasonNewDeviceAvailable: + case AVAudioSessionRouteChangeReasonNewDeviceAvailable: { NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable"); NSLog(@"Headphone/Line plugged in"); - break; + }; break; - case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: + case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: { NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable"); NSLog(@"Headphone/Line was pulled. Resuming video play...."); if (_is_video_playing()) { @@ -605,24 +582,22 @@ static void clear_touches() { NSLog(@"resumed play"); }); }; - break; + }; break; - case AVAudioSessionRouteChangeReasonCategoryChange: + case AVAudioSessionRouteChangeReasonCategoryChange: { // called at start - also when other audio wants to play NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange"); - break; + }; break; } } // When created via code however, we get initWithFrame --(id)initWithFrame:(CGRect)frame -{ +-(id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; _instance = self; printf("after init super %p\n", self); - if(self != nil) - { + if(self != nil) { self = [self initGLES]; printf("after init gles %p\n", self); } @@ -631,8 +606,8 @@ static void clear_touches() { printf("******** adding observer for sound routing changes\n"); [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) - name:AVAudioSessionRouteChangeNotification - object:nil]; + name:AVAudioSessionRouteChangeNotification + object:nil]; //self.autoresizesSubviews = YES; //[self setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth]; @@ -649,12 +624,10 @@ static void clear_touches() { // } // Stop animating and release resources when they are no longer needed. -- (void)dealloc -{ +- (void)dealloc { [self stopAnimation]; - if([EAGLContext currentContext] == context) - { + if([EAGLContext currentContext] == context) { [EAGLContext setCurrentContext:nil]; } @@ -665,24 +638,24 @@ static void clear_touches() { } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object - change:(NSDictionary *)change context:(void *)context { + change:(NSDictionary *)change context:(void *)context { if (object == _instance.avPlayerItem && [keyPath isEqualToString:@"status"]) { - if (_instance.avPlayerItem.status == AVPlayerStatusFailed || _instance.avPlayer.status == AVPlayerStatusFailed) { - _stop_video(); - video_found_error = true; - } - - if(_instance.avPlayer.status == AVPlayerStatusReadyToPlay && - _instance.avPlayerItem.status == AVPlayerItemStatusReadyToPlay && - CMTIME_COMPARE_INLINE(video_current_time, ==, kCMTimeZero)) { - - //NSLog(@"time: %@", video_current_time); - - [_instance.avPlayer seekToTime:video_current_time]; - video_current_time = kCMTimeZero; + if (_instance.avPlayerItem.status == AVPlayerStatusFailed || _instance.avPlayer.status == AVPlayerStatusFailed) { + _stop_video(); + video_found_error = true; } - } + + if(_instance.avPlayer.status == AVPlayerStatusReadyToPlay && + _instance.avPlayerItem.status == AVPlayerItemStatusReadyToPlay && + CMTIME_COMPARE_INLINE(video_current_time, ==, kCMTimeZero)) { + + //NSLog(@"time: %@", video_current_time); + + [_instance.avPlayer seekToTime:video_current_time]; + video_current_time = kCMTimeZero; + } + } if (object == _instance.avPlayer && [keyPath isEqualToString:@"rate"]) { NSLog(@"Player playback rate changed: %.5f", _instance.avPlayer.rate); @@ -698,40 +671,40 @@ static void clear_touches() { } - (void)playerItemDidReachEnd:(NSNotification *)notification { - _stop_video(); + _stop_video(); } /* - (void)moviePlayBackDidFinish:(NSNotification*)notification { - NSNumber* reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]; - switch ([reason intValue]) { - case MPMovieFinishReasonPlaybackEnded: - //NSLog(@"Playback Ended"); - break; - case MPMovieFinishReasonPlaybackError: - //NSLog(@"Playback Error"); - video_found_error = true; - break; - case MPMovieFinishReasonUserExited: - //NSLog(@"User Exited"); - video_found_error = true; - break; - default: - //NSLog(@"Unsupported reason!"); - break; - } + NSNumber* reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]; + switch ([reason intValue]) { + case MPMovieFinishReasonPlaybackEnded: + //NSLog(@"Playback Ended"); + break; + case MPMovieFinishReasonPlaybackError: + //NSLog(@"Playback Error"); + video_found_error = true; + break; + case MPMovieFinishReasonUserExited: + //NSLog(@"User Exited"); + video_found_error = true; + break; + default: + //NSLog(@"Unsupported reason!"); + break; + } - MPMoviePlayerController *player = [notification object]; + MPMoviePlayerController *player = [notification object]; - [[NSNotificationCenter defaultCenter] - removeObserver:self - name:MPMoviePlayerPlaybackDidFinishNotification - object:player]; + [[NSNotificationCenter defaultCenter] + removeObserver:self + name:MPMoviePlayerPlaybackDidFinishNotification + object:player]; - [_instance.moviePlayerController stop]; - [_instance.moviePlayerController.view removeFromSuperview]; + [_instance.moviePlayerController stop]; + [_instance.moviePlayerController.view removeFromSuperview]; //[[MPMusicPlayerController applicationMusicPlayer] setVolume: video_previous_volume]; video_playing = false; diff --git a/platform/iphone/icloud.mm b/platform/iphone/icloud.mm index b88af468fd..94286ceabe 100644 --- a/platform/iphone/icloud.mm +++ b/platform/iphone/icloud.mm @@ -44,14 +44,14 @@ extern "C" { ICloud* ICloud::instance = NULL; void ICloud::_bind_methods() { - ObjectTypeDB::bind_method(_MD("remove_key"),&ICloud::remove_key); - ObjectTypeDB::bind_method(_MD("set_key_values"),&ICloud::set_key_values); - ObjectTypeDB::bind_method(_MD("get_key_value"),&ICloud::get_key_value); - ObjectTypeDB::bind_method(_MD("synchronize_key_values"),&ICloud::synchronize_key_values); - ObjectTypeDB::bind_method(_MD("get_all_key_values"),&ICloud::get_all_key_values); + ObjectTypeDB::bind_method(_MD("remove_key"), &ICloud::remove_key); + ObjectTypeDB::bind_method(_MD("set_key_values"), &ICloud::set_key_values); + ObjectTypeDB::bind_method(_MD("get_key_value"), &ICloud::get_key_value); + ObjectTypeDB::bind_method(_MD("synchronize_key_values"), &ICloud::synchronize_key_values); + ObjectTypeDB::bind_method(_MD("get_all_key_values"), &ICloud::get_all_key_values); - ObjectTypeDB::bind_method(_MD("get_pending_event_count"),&ICloud::get_pending_event_count); - ObjectTypeDB::bind_method(_MD("pop_pending_event"),&ICloud::pop_pending_event); + ObjectTypeDB::bind_method(_MD("get_pending_event_count"), &ICloud::get_pending_event_count); + ObjectTypeDB::bind_method(_MD("pop_pending_event"), &ICloud::pop_pending_event); }; int ICloud::get_pending_event_count() { @@ -76,8 +76,7 @@ Variant nsobject_to_variant(NSObject* object) { if ([object isKindOfClass:[NSString class]]) { const char* str = [(NSString*)object UTF8String]; return String::utf8(str != NULL ? str : ""); - } - else if ([object isKindOfClass:[NSData class]]) { + } else if ([object isKindOfClass:[NSData class]]) { ByteArray ret; NSData* data = (NSData*)object; if ([data length] > 0) { @@ -88,8 +87,7 @@ Variant nsobject_to_variant(NSObject* object) { } } return ret; - } - else if ([object isKindOfClass:[NSArray class]]) { + } else if ([object isKindOfClass:[NSArray class]]) { Array result; NSArray* array = (NSArray*)object; for (unsigned int i = 0; i < [array count]; ++i) { @@ -97,8 +95,7 @@ Variant nsobject_to_variant(NSObject* object) { result.push_back(nsobject_to_variant(value)); } return result; - } - else if ([object isKindOfClass:[NSDictionary class]]) { + } else if ([object isKindOfClass:[NSDictionary class]]) { Dictionary result; NSDictionary* dic = (NSDictionary*)object; @@ -112,8 +109,7 @@ Variant nsobject_to_variant(NSObject* object) { result[nsobject_to_variant(k)] = nsobject_to_variant(v); } return result; - } - else if ([object isKindOfClass:[NSNumber class]]) { + } else if ([object isKindOfClass:[NSNumber class]]) { //Every type except numbers can reliably identify its type. The following is comparing to the *internal* representation, which isn't guaranteed to match the type that was used to create it, and is not advised, particularly when dealing with potential platform differences (ie, 32/64 bit) //To avoid errors, we'll cast as broadly as possible, and only return int or float. //bool, char, int, uint, longlong -> int @@ -121,37 +117,28 @@ Variant nsobject_to_variant(NSObject* object) { NSNumber* num = (NSNumber*)object; if(strcmp([num objCType], @encode(BOOL)) == 0) { 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]); - } - else if(strcmp([num objCType], @encode(int)) == 0) { + } else if(strcmp([num objCType], @encode(int)) == 0) { 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]); - } - else if(strcmp([num objCType], @encode(long long)) == 0) { + } else if(strcmp([num objCType], @encode(long long)) == 0) { 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]); - } - else if(strcmp([num objCType], @encode(double)) == 0) { + } else if(strcmp([num objCType], @encode(double)) == 0) { return Variant((float)[num doubleValue]); } - } - else if ([object isKindOfClass:[NSDate class]]) { + } else if ([object isKindOfClass:[NSDate class]]) { //this is a type that icloud supports...but how did you submit it in the first place? //I guess this is a type that *might* show up, if you were, say, trying to make your game //compatible with existing cloud data written by another engine's version of your game WARN_PRINT("NSDate unsupported, returning null Variant") return Variant(); - } - else if ([object isKindOfClass:[NSNull class]] or object == nil) { + } else if ([object isKindOfClass:[NSNull class]] or object == nil) { return Variant(); - } - else { + } else { WARN_PRINT("Trying to convert unknown NSObject type to Variant"); return Variant(); } @@ -160,17 +147,13 @@ Variant nsobject_to_variant(NSObject* object) { NSObject* variant_to_nsobject(Variant v) { if (v.get_type() == Variant::STRING) { return [[[NSString alloc] initWithUTF8String:((String)v).utf8().get_data()] autorelease]; - } - else if (v.get_type() == Variant::REAL) { + } else if (v.get_type() == Variant::REAL) { return [NSNumber numberWithDouble:(double)v]; - } - else if (v.get_type() == Variant::INT) { + } else if (v.get_type() == Variant::INT) { return [NSNumber numberWithLongLong:(long)(int)v]; - } - else if (v.get_type() == Variant::BOOL) { + } else if (v.get_type() == Variant::BOOL) { 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]; Dictionary dic = v; Array keys = dic.keys(); @@ -185,8 +168,7 @@ NSObject* variant_to_nsobject(Variant v) { [result setObject:value forKey:key]; } return result; - } - else if (v.get_type() == Variant::ARRAY) { + } else if (v.get_type() == Variant::ARRAY) { NSMutableArray* result = [[[NSMutableArray alloc] init] autorelease]; Array arr = v; for (unsigned int i = 0; i < arr.size(); ++i) { @@ -198,8 +180,7 @@ NSObject* variant_to_nsobject(Variant v) { [result addObject:value]; } return result; - } - else if (v.get_type() == Variant::RAW_ARRAY) { + } else if (v.get_type() == Variant::RAW_ARRAY) { ByteArray arr = v; ByteArray::Read r = arr.read(); NSData* result = [NSData dataWithBytes:r.ptr() length:arr.size()]; @@ -296,8 +277,7 @@ Error ICloud::synchronize_key_values() { BOOL result = [store synchronize]; if (result == YES) { return OK; - } - else { + } else { return FAILED; } } @@ -306,14 +286,14 @@ Error ICloud::initial_sync() { //you sometimes have to write something to the store to get it to download new data. go apple! NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore]; if ([store boolForKey:@"isb"]) - { - [store setBool:NO forKey:@"isb"]; - } - else - { - [store setBool:YES forKey:@"isb"]; - } - return synchronize(); + { + [store setBool:NO forKey:@"isb"]; + } + else + { + [store setBool:YES forKey:@"isb"]; + } + return synchronize(); } */ ICloud::ICloud() { @@ -340,14 +320,11 @@ ICloud::ICloud() { if (change == NSUbiquitousKeyValueStoreServerChange) { reason = "server"; - } - else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) { + } else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) { reason = "initial_sync"; - } - else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) { + } else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) { reason = "quota_violation"; - } - else if (change == NSUbiquitousKeyValueStoreAccountChange) { + } else if (change == NSUbiquitousKeyValueStoreAccountChange) { reason = "account"; } diff --git a/platform/iphone/in_app_store.mm b/platform/iphone/in_app_store.mm index bef01a9724..bf4073c5d6 100644 --- a/platform/iphone/in_app_store.mm +++ b/platform/iphone/in_app_store.mm @@ -35,8 +35,8 @@ #include "in_app_store.h" extern "C" { -#import -#import + #import + #import }; bool auto_finish_transactions = true; @@ -50,8 +50,7 @@ NSMutableDictionary* pending_transactions = [NSMutableDictionary dictionary]; // SKProduct extension //----------------------------------// @implementation SKProduct (LocalizedPrice) -- (NSString *)localizedPrice -{ +- (NSString *)localizedPrice { NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; @@ -164,95 +163,91 @@ Error InAppStore::request_product_info(Variant p_params) { - (void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray*) transactions { - printf("transactions updated!\n"); + printf("transactions updated!\n"); for (SKPaymentTransaction* transaction in transactions) { switch (transaction.transactionState) { + case SKPaymentTransactionStatePurchased: { + printf("status purchased!\n"); + String pid = String::utf8([transaction.payment.productIdentifier UTF8String]); + String transactionId = String::utf8([transaction.transactionIdentifier UTF8String]); + InAppStore::get_singleton()->_record_purchase(pid); + Dictionary ret; + ret["type"] = "purchase"; + ret["result"] = "ok"; + ret["product_id"] = pid; + ret["transaction_id"] = transactionId; - case SKPaymentTransactionStatePurchased: { - printf("status purchased!\n"); - String pid = String::utf8([transaction.payment.productIdentifier UTF8String]); - String transactionId = String::utf8([transaction.transactionIdentifier UTF8String]); - InAppStore::get_singleton()->_record_purchase(pid); - Dictionary ret; - ret["type"] = "purchase"; - ret["result"] = "ok"; - ret["product_id"] = pid; - ret["transaction_id"] = transactionId; + NSData* receipt = nil; + int sdk_version = 6; - NSData* receipt = nil; - int sdk_version = 6; + if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){ - if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){ + NSURL *receiptFileURL = nil; + NSBundle *bundle = [NSBundle mainBundle]; + if ([bundle respondsToSelector:@selector(appStoreReceiptURL)]) { - NSURL *receiptFileURL = nil; - NSBundle *bundle = [NSBundle mainBundle]; - if ([bundle respondsToSelector:@selector(appStoreReceiptURL)]) { + // Get the transaction receipt file path location in the app bundle. + receiptFileURL = [bundle appStoreReceiptURL]; - // Get the transaction receipt file path location in the app bundle. - receiptFileURL = [bundle appStoreReceiptURL]; + // Read in the contents of the transaction file. + receipt = [NSData dataWithContentsOfURL:receiptFileURL]; + sdk_version = 7; - // Read in the contents of the transaction file. - receipt = [NSData dataWithContentsOfURL:receiptFileURL]; - sdk_version = 7; + } else { + // Fall back to deprecated transaction receipt, + // which is still available in iOS 7. - } else { - // Fall back to deprecated transaction receipt, - // which is still available in iOS 7. + // Use SKPaymentTransaction's transactionReceipt. + receipt = transaction.transactionReceipt; + } - // Use SKPaymentTransaction's transactionReceipt. - receipt = transaction.transactionReceipt; - } + } else { + receipt = transaction.transactionReceipt; + } - }else{ - receipt = transaction.transactionReceipt; - } + NSString* receipt_to_send = nil; + if (receipt != nil) { + receipt_to_send = [receipt description]; + } + Dictionary receipt_ret; + receipt_ret["receipt"] = String::utf8(receipt_to_send != nil ? [receipt_to_send UTF8String] : ""); + receipt_ret["sdk"] = sdk_version; + ret["receipt"] = receipt_ret; - NSString* receipt_to_send = nil; - if (receipt != nil) - { - receipt_to_send = [receipt description]; - } - Dictionary receipt_ret; - receipt_ret["receipt"] = String::utf8(receipt_to_send != nil ? [receipt_to_send UTF8String] : ""); - receipt_ret["sdk"] = sdk_version; - ret["receipt"] = receipt_ret; + InAppStore::get_singleton()->_post_event(ret); - InAppStore::get_singleton()->_post_event(ret); + if (auto_finish_transactions){ + [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; + } else { + [pending_transactions setObject:transaction forKey:transaction.payment.productIdentifier]; + } - if (auto_finish_transactions){ - [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; - } - else{ - [pending_transactions setObject:transaction forKey:transaction.payment.productIdentifier]; - } + #ifdef MODULE_FUSEBOXX_ENABLED + printf("Registering transaction on Fuseboxx!\n"); + [FuseSDK registerInAppPurchase: transaction]; + #endif + }; break; + case SKPaymentTransactionStateFailed: { + printf("status transaction failed!\n"); + String pid = String::utf8([transaction.payment.productIdentifier UTF8String]); + Dictionary ret; + ret["type"] = "purchase"; + ret["result"] = "error"; + ret["product_id"] = pid; + InAppStore::get_singleton()->_post_event(ret); + [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; + }; break; + case SKPaymentTransactionStateRestored: { + printf("status transaction restored!\n"); + String pid = String::utf8([transaction.originalTransaction.payment.productIdentifier UTF8String]); + InAppStore::get_singleton()->_record_purchase(pid); + [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; + }; break; + default: { + printf("status default %i!\n", (int)transaction.transactionState); - #ifdef MODULE_FUSEBOXX_ENABLED - printf("Registering transaction on Fuseboxx!\n"); - [FuseSDK registerInAppPurchase: transaction]; - #endif - } break; - case SKPaymentTransactionStateFailed: { - printf("status transaction failed!\n"); - String pid = String::utf8([transaction.payment.productIdentifier UTF8String]); - Dictionary ret; - ret["type"] = "purchase"; - ret["result"] = "error"; - ret["product_id"] = pid; - InAppStore::get_singleton()->_post_event(ret); - [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; - } break; - case SKPaymentTransactionStateRestored: { - printf("status transaction restored!\n"); - String pid = String::utf8([transaction.originalTransaction.payment.productIdentifier UTF8String]); - InAppStore::get_singleton()->_record_purchase(pid); - [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; - } break; - - default: - printf("status default %i!\n", (int)transaction.transactionState); - - break; + }; break; }; }; }; @@ -266,7 +261,7 @@ Error InAppStore::purchase(Variant p_params) { if (![SKPaymentQueue canMakePayments]) return ERR_UNAVAILABLE; - printf("purchasing!\n"); + printf("purchasing!\n"); Dictionary params = p_params; ERR_FAIL_COND_V(!params.has("product_id"), ERR_INVALID_PARAMETER); @@ -274,7 +269,7 @@ Error InAppStore::purchase(Variant p_params) { SKPayment *payment = [SKPayment paymentWithProductIdentifier:pid]; SKPaymentQueue* defq = [SKPaymentQueue defaultQueue]; [defq addPayment:payment]; - printf("purchase sent!\n"); + printf("purchase sent!\n"); return OK; }; @@ -317,20 +312,20 @@ InAppStore::InAppStore() { TransObserver* observer = [[TransObserver alloc] init]; [[SKPaymentQueue defaultQueue] addTransactionObserver:observer]; - //pending_transactions = [NSMutableDictionary dictionary]; + //pending_transactions = [NSMutableDictionary dictionary]; }; 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]]; - [pending_transactions removeObjectForKey:prod_id]; + [pending_transactions removeObjectForKey:prod_id]; } }; void InAppStore::set_auto_finish_transaction(bool b){ - auto_finish_transactions = b; + auto_finish_transactions = b; } InAppStore::~InAppStore() { diff --git a/platform/iphone/ios.mm b/platform/iphone/ios.mm index e7e4d9191c..e63ba18286 100644 --- a/platform/iphone/ios.mm +++ b/platform/iphone/ios.mm @@ -43,14 +43,11 @@ String iOS::get_rate_url(int p_app_id) const { //ios7 before String ret = templ; - // iOS 7 needs a different templateReviewURL @see https://github.com/arashpayan/appirater/issues/131 - 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 ret = templ_iOS7; - } + } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) { // iOS 8 needs a different templateReviewURL also @see https://github.com/arashpayan/appirater/issues/182 - else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) - { ret = templ_iOS8; } diff --git a/platform/iphone/main.m b/platform/iphone/main.m index 02a45737c5..68433fd468 100644 --- a/platform/iphone/main.m +++ b/platform/iphone/main.m @@ -33,8 +33,7 @@ int gargc; char** gargv; -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { printf("*********** main.m\n"); gargc = argc; gargv = argv; diff --git a/platform/iphone/view_controller.mm b/platform/iphone/view_controller.mm index 8b3dc7c984..9c0bd43c14 100644 --- a/platform/iphone/view_controller.mm +++ b/platform/iphone/view_controller.mm @@ -32,42 +32,42 @@ extern "C" { -int add_path(int, char**); -int add_cmdline(int, char**); + int add_path(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; - - 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]; + NSString* str = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_path"]; if (!str) - continue; - [str retain]; // @todo delete these at some point + 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; + + return p_argc; }; - p_args[p_argc] = NULL; + int add_cmdline(int p_argc, char** p_args) { - return p_argc; -}; + 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; + }; }; @@ -90,53 +90,52 @@ int add_cmdline(int p_argc, char** p_args) { NSArray* arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"]; switch(p_orientation) { - case UIInterfaceOrientationLandscapeLeft: - return [arr indexOfObject:@"UIInterfaceOrientationLandscapeLeft"] != NSNotFound ? YES : NO; + case UIInterfaceOrientationLandscapeLeft: + return [arr indexOfObject:@"UIInterfaceOrientationLandscapeLeft"] != NSNotFound ? YES : NO; - case UIInterfaceOrientationLandscapeRight: - return [arr indexOfObject:@"UIInterfaceOrientationLandscapeRight"] != NSNotFound ? YES : NO; + case UIInterfaceOrientationLandscapeRight: + return [arr indexOfObject:@"UIInterfaceOrientationLandscapeRight"] != NSNotFound ? YES : NO; - case UIInterfaceOrientationPortrait: - return [arr indexOfObject:@"UIInterfaceOrientationPortrait"] != NSNotFound ? YES : NO; + case UIInterfaceOrientationPortrait: + return [arr indexOfObject:@"UIInterfaceOrientationPortrait"] != NSNotFound ? YES : NO; - case UIInterfaceOrientationPortraitUpsideDown: - return [arr indexOfObject:@"UIInterfaceOrientationPortraitUpsideDown"] != NSNotFound ? YES : NO; + case UIInterfaceOrientationPortraitUpsideDown: + return [arr indexOfObject:@"UIInterfaceOrientationPortraitUpsideDown"] != NSNotFound ? YES : NO; - default: - return NO; + default: + return NO; } }; uint8_t supported = OSIPhone::get_singleton()->get_orientations(); switch(p_orientation) { - case UIInterfaceOrientationLandscapeLeft: - return supported & (1<game_center_closed();}];//version for signaling when overlay is completely gone - GameCenter::get_singleton()->game_center_closed(); - [gameCenterViewController dismissViewControllerAnimated:YES completion:nil]; + //[gameCenterViewController dismissViewControllerAnimated:YES completion:^{GameCenter::get_singleton()->game_center_closed();}];//version for signaling when overlay is completely gone + GameCenter::get_singleton()->game_center_closed(); + [gameCenterViewController dismissViewControllerAnimated:YES completion:nil]; } #endif diff --git a/platform/osx/godot_main_osx.mm b/platform/osx/godot_main_osx.mm index 8eedd7f6fc..d77a1b5678 100644 --- a/platform/osx/godot_main_osx.mm +++ b/platform/osx/godot_main_osx.mm @@ -39,30 +39,30 @@ int main(int argc, char** argv) { int first_arg = 1; const char* dbg_arg = "-NSDocumentRevisionsDebugMode"; printf("arguments\n"); - for (int i=0; i=1 && argv[0][0]=='/') { + if (argc >= 1 && argv[0][0] == '/') { //potentially launched from finder int len = strlen(argv[0]); while (len--) { if (argv[0][len] == '/') break; } - if (len>=0) { + if (len >= 0) { char *path = (char *)malloc(len+1); 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 strcpy(pathinfo, path); strcat(pathinfo, "/../Info.plist"); - FILE*f=fopen(pathinfo,"rb"); + FILE*f=fopen(pathinfo, "rb"); if (f) { //running from app bundle, as Info.plist was found fclose(f); @@ -74,15 +74,12 @@ int main(int argc, char** argv) { free(path); free(pathinfo); } - - - } 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) return 255; diff --git a/platform/osx/godot_osx.mm b/platform/osx/godot_osx.mm index 2296fb016f..2292508357 100644 --- a/platform/osx/godot_osx.mm +++ b/platform/osx/godot_osx.mm @@ -43,18 +43,18 @@ static BOOL gCalledAppMainline = FALSE; static NSString *getApplicationName(void) { - const NSDictionary *dict; - NSString *appName = 0; + const NSDictionary *dict; + NSString *appName = 0; - /* Determine the application name */ - dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); - if (dict) - appName = [dict objectForKey: @"CFBundleName"]; + /* Determine the application name */ + dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); + if (dict) + appName = [dict objectForKey: @"CFBundleName"]; - if (![appName length]) - appName = [[NSProcessInfo processInfo] processName]; + if (![appName length]) + appName = [[NSProcessInfo processInfo] processName]; - return appName; + return appName; } /* The main class of the application, the application's delegate */ @@ -62,97 +62,97 @@ static NSString *getApplicationName(void) static void setApplicationMenu(void) { - /* warning: this code is very odd */ - NSMenu *appleMenu; - NSMenuItem *menuItem; - NSString *title; - NSString *appName; + /* warning: this code is very odd */ + NSMenu *appleMenu; + NSMenuItem *menuItem; + NSString *title; + NSString *appName; - appName = getApplicationName(); - appleMenu = [[NSMenu alloc] initWithTitle:@""]; + appName = getApplicationName(); + appleMenu = [[NSMenu alloc] initWithTitle:@""]; - /* Add menu items */ - title = [@"About " stringByAppendingString:appName]; - [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; + /* Add menu items */ + title = [@"About " stringByAppendingString:appName]; + [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; - [appleMenu addItem:[NSMenuItem separatorItem]]; + [appleMenu addItem:[NSMenuItem separatorItem]]; - title = [@"Hide " stringByAppendingString:appName]; - [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; + title = [@"Hide " stringByAppendingString:appName]; + [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; - menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; - [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; + menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; + [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; - [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; + [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; - [appleMenu addItem:[NSMenuItem separatorItem]]; + [appleMenu addItem:[NSMenuItem separatorItem]]; - title = [@"Quit " stringByAppendingString:appName]; - [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; + title = [@"Quit " stringByAppendingString:appName]; + [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; - /* Put menu into the menubar */ - menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; - [menuItem setSubmenu:appleMenu]; - [[NSApp mainMenu] addItem:menuItem]; + /* Put menu into the menubar */ + menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; + [menuItem setSubmenu:appleMenu]; + [[NSApp mainMenu] addItem:menuItem]; - /* Tell the application object that this is now the application menu */ - [NSApp setAppleMenu:appleMenu]; + /* Tell the application object that this is now the application menu */ + [NSApp setAppleMenu:appleMenu]; - /* Finally give up our references to the objects */ - [appleMenu release]; - [menuItem release]; + /* Finally give up our references to the objects */ + [appleMenu release]; + [menuItem release]; } /* Create a window menu */ static void setupWindowMenu(void) { - NSMenu *windowMenu; - NSMenuItem *windowMenuItem; - NSMenuItem *menuItem; + NSMenu *windowMenu; + NSMenuItem *windowMenuItem; + NSMenuItem *menuItem; - windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; + windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; - /* "Minimize" item */ - menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; - [windowMenu addItem:menuItem]; - [menuItem release]; + /* "Minimize" item */ + menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; + [windowMenu addItem:menuItem]; + [menuItem release]; - /* Put menu into the menubar */ - windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""]; - [windowMenuItem setSubmenu:windowMenu]; - [[NSApp mainMenu] addItem:windowMenuItem]; + /* Put menu into the menubar */ + windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""]; + [windowMenuItem setSubmenu:windowMenu]; + [[NSApp mainMenu] addItem:windowMenuItem]; - /* Tell the application object that this is now the window menu */ - [NSApp setWindowsMenu:windowMenu]; + /* Tell the application object that this is now the window menu */ + [NSApp setWindowsMenu:windowMenu]; - /* Finally give up our references to the objects */ - [windowMenu release]; - [windowMenuItem release]; + /* Finally give up our references to the objects */ + [windowMenu release]; + [windowMenuItem release]; } /* Replacement for NSApplicationMain */ static void CustomApplicationMain (int argc, char **argv) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; GodotMain *main; - /* Ensure the application object is initialised */ - [NSApplication sharedApplication]; + /* Ensure the application object is initialised */ + [NSApplication sharedApplication]; - /* Set up the menubar */ - [NSApp setMainMenu:[[NSMenu alloc] init]]; - setApplicationMenu(); - setupWindowMenu(); + /* Set up the menubar */ + [NSApp setMainMenu:[[NSMenu alloc] init]]; + setApplicationMenu(); + setupWindowMenu(); main = [[main alloc] init]; [NSApp setDelegate:main]; - /* Start the main event loop */ - [NSApp run]; + /* Start the main event loop */ + [NSApp run]; [main release]; - [pool release]; + [pool release]; } extern int godot_main(int argc, char** argv); @@ -160,10 +160,10 @@ extern int godot_main(int argc, char** argv); /* Called when the internal event loop has just started running */ - (void) applicationDidFinishLaunching: (NSNotification *) note { - int status; + int status; - /* Hand off to main application code */ - gCalledAppMainline = TRUE; + /* Hand off to main application code */ + gCalledAppMainline = TRUE; int ret = godot_main(global_argc, global_argv); @@ -172,44 +172,43 @@ extern int godot_main(int argc, char** argv); @end #ifdef main -# undef main +#undef main #endif - int main (int argc, char **argv) { - /* Copy the arguments into a global variable */ - /* This is passed if we are launched by double-clicking */ - if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { - global_argv = (char **) malloc(sizeof (char *) * 2); - global_argv[0] = argv[0]; - global_argv[1] = NULL; - global_argc = 1; + /* Copy the arguments into a global variable */ + /* This is passed if we are launched by double-clicking */ + if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { + global_argv = (char **) malloc(sizeof (char *) * 2); + global_argv[0] = argv[0]; + global_argv[1] = NULL; + global_argc = 1; - // chdir to binary's dir when launched from finder - int len = strlen(global_argv[0]); + // chdir to binary's dir when launched from finder + int len = strlen(global_argv[0]); - while (len--){ - if (global_argv[0][len] == '/') break; - } + while (len--){ + if (global_argv[0][len] == '/') break; + } - if (len>=0) { - char *path = (char *)malloc(len+1); - memcpy(path, global_argv[0], len); - path[len]=0; - printf("Path: %s\n", path); - chdir(path); - } + if (len>=0) { + char *path = (char *)malloc(len+1); + memcpy(path, global_argv[0], len); + path[len]=0; + printf("Path: %s\n", path); + chdir(path); + } - } else { - int i; - global_argc = argc; - global_argv = (char **) malloc(sizeof (char *) * (argc+1)); - for (i = 0; i <= argc; i++) - global_argv[i] = argv[i]; - } + } else { + int i; + global_argc = argc; + global_argv = (char **) malloc(sizeof (char *) * (argc+1)); + for (i = 0; i <= argc; i++) + global_argv[i] = argv[i]; + } - CustomApplicationMain (argc, argv); - return 0; + CustomApplicationMain (argc, argv); + return 0; } diff --git a/platform/osx/os_osx.mm b/platform/osx/os_osx.mm index aba810a84f..fe61c3a0c9 100644 --- a/platform/osx/os_osx.mm +++ b/platform/osx/os_osx.mm @@ -86,32 +86,30 @@ static NSRect convertRectToBacking(NSRect contentRect) { #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 - if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6) - return [OS_OSX::singleton->window_view convertRectToBacking:contentRect]; - else + if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6) + return [OS_OSX::singleton->window_view convertRectToBacking:contentRect]; + else #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/ - return contentRect; + return contentRect; } -static InputModifierState translateFlags(NSUInteger flags) -{ - InputModifierState mod; +static InputModifierState translateFlags(NSUInteger flags) { + InputModifierState mod; + mod.shift = (flags & NSShiftKeyMask); + mod.control = (flags & NSControlKeyMask); + mod.alt = (flags & NSAlternateKeyMask); + mod.meta = (flags & NSCommandKeyMask); - mod.shift = (flags & NSShiftKeyMask); - mod.control = (flags & NSControlKeyMask); - mod.alt = (flags & NSAlternateKeyMask); - mod.meta = (flags & NSCommandKeyMask); - - return mod; + return mod; } -static int mouse_x=0; -static int mouse_y=0; -static int prev_mouse_x=0; -static int prev_mouse_y=0; -static int button_mask=0; +static int mouse_x = 0; +static int mouse_y = 0; +static int prev_mouse_x = 0; +static int prev_mouse_y = 0; +static int button_mask = 0; @interface GodotApplication : NSApplication @@ -122,12 +120,11 @@ static int button_mask=0; // From http://cocoadev.com/index.pl?GameKeyboardHandlingAlmost // This works around an AppKit bug, where key up events while holding // down the command key don't get sent to the key window. -- (void)sendEvent:(NSEvent *)event -{ - if ([event type] == NSKeyUp && ([event modifierFlags] & NSCommandKeyMask)) - [[self keyWindow] sendEvent:event]; - else - [super sendEvent:event]; +- (void)sendEvent:(NSEvent *)event { + if ([event type] == NSKeyUp && ([event modifierFlags] & NSCommandKeyMask)) + [[self keyWindow] sendEvent:event]; + else + [super sendEvent:event]; } @end @@ -137,121 +134,104 @@ static int button_mask=0; @implementation GodotApplicationDelegate -- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender -{ +- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender { if (OS_OSX::singleton->get_main_loop()) OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST); return NSTerminateCancel; } -- (void)applicationDidHide:(NSNotification *)notification -{ - /* _Godotwindow* window; +- (void)applicationDidHide:(NSNotification *)notification { +/* + _Godotwindow* window; - for (window = _Godot.windowListHead; window; window = window->next) - _GodotInputWindowVisibility(window, GL_FALSE); - */ + for (window = _Godot.windowListHead; window; window = window->next) + _GodotInputWindowVisibility(window, GL_FALSE); +*/ } -- (void)applicationDidUnhide:(NSNotification *)notification -{ - /* - _Godotwindow* window; +- (void)applicationDidUnhide:(NSNotification *)notification { +/* + _Godotwindow* window; - for (window = _Godot.windowListHead; window; window = window->next) - { - if ([window_object isVisible]) - _GodotInputWindowVisibility(window, GL_TRUE); - } - */ + for (window = _Godot.windowListHead; window; window = window->next) + { + if ([window_object isVisible]) + _GodotInputWindowVisibility(window, GL_TRUE); + } +*/ } -- (void)applicationDidChangeScreenParameters:(NSNotification *) notification -{ - //_GodotInputMonitorChange(); +- (void)applicationDidChangeScreenParameters:(NSNotification *) notification { + //_GodotInputMonitorChange(); } @end -@interface GodotWindowDelegate : NSObject -{ - // _Godotwindow* window; +@interface GodotWindowDelegate : NSObject { + //_Godotwindow* window; } @end @implementation GodotWindowDelegate - -- (BOOL)windowShouldClose:(id)sender -{ - //_GodotInputWindowCloseRequest(window); +- (BOOL)windowShouldClose:(id)sender { + //_GodotInputWindowCloseRequest(window); if (OS_OSX::singleton->get_main_loop()) OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST); - return NO; + return NO; } +- (void)windowDidResize:(NSNotification *)notification { + [OS_OSX::singleton->context update]; + const NSRect contentRect = [OS_OSX::singleton->window_view frame]; + const NSRect fbRect = contentRect;//convertRectToBacking(contentRect); + OS_OSX::singleton->window_size.width = fbRect.size.width*OS_OSX::singleton->display_scale; + OS_OSX::singleton->window_size.height = fbRect.size.height*OS_OSX::singleton->display_scale; -- (void)windowDidResize:(NSNotification *)notification -{ - [OS_OSX::singleton->context update]; + //_GodotInputFramebufferSize(window, fbRect.size.width, fbRect.size.height); + //_GodotInputWindowSize(window, contentRect.size.width, contentRect.size.height); + //_GodotInputWindowDamage(window); - const NSRect contentRect = [OS_OSX::singleton->window_view frame]; - const NSRect fbRect = contentRect;//convertRectToBacking(contentRect); - - OS_OSX::singleton->window_size.width=fbRect.size.width*OS_OSX::singleton->display_scale; - OS_OSX::singleton->window_size.height=fbRect.size.height*OS_OSX::singleton->display_scale; - - - // _GodotInputFramebufferSize(window, fbRect.size.width, fbRect.size.height); - // _GodotInputWindowSize(window, contentRect.size.width, contentRect.size.height); - //_GodotInputWindowDamage(window); - - //if (window->cursorMode == Godot_CURSOR_DISABLED) - // centerCursor(window); + //if (window->cursorMode == Godot_CURSOR_DISABLED) + // centerCursor(window); } -- (void)windowDidMove:(NSNotification *)notification -{ - // [window->nsgl.context update]; +- (void)windowDidMove:(NSNotification *)notification { + //[window->nsgl.context update]; - // int x, y; - // _GodotPlatformGetWindowPos(window, &x, &y); - // _GodotInputWindowPos(window, x, y); + //int x, y; + //_GodotPlatformGetWindowPos(window, &x, &y); + //_GodotInputWindowPos(window, x, y); - //if (window->cursorMode == Godot_CURSOR_DISABLED) - // centerCursor(window); + //if (window->cursorMode == Godot_CURSOR_DISABLED) + // centerCursor(window); } -- (void)windowDidBecomeKey:(NSNotification *)notification -{ - // _GodotInputWindowFocus(window, GL_TRUE); - // _GodotPlatformSetCursorMode(window, window->cursorMode); +- (void)windowDidBecomeKey:(NSNotification *)notification { + //_GodotInputWindowFocus(window, GL_TRUE); + //_GodotPlatformSetCursorMode(window, window->cursorMode); if (OS_OSX::singleton->get_main_loop()) OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN); } -- (void)windowDidResignKey:(NSNotification *)notification -{ - // _GodotInputWindowFocus(window, GL_FALSE); - // _GodotPlatformSetCursorMode(window, Godot_CURSOR_NORMAL); +- (void)windowDidResignKey:(NSNotification *)notification { + //_GodotInputWindowFocus(window, GL_FALSE); + //_GodotPlatformSetCursorMode(window, Godot_CURSOR_NORMAL); if (OS_OSX::singleton->get_main_loop()) OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT); } -- (void)windowDidMiniaturize:(NSNotification*)notification -{ +- (void)windowDidMiniaturize:(NSNotification*)notification { OS_OSX::singleton->wm_minimized(true); if (OS_OSX::singleton->get_main_loop()) OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT); }; -- (void)windowDidDeminiaturize:(NSNotification*)notification -{ - +- (void)windowDidDeminiaturize:(NSNotification*)notification { OS_OSX::singleton->wm_minimized(false); if (OS_OSX::singleton->get_main_loop()) OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN); @@ -259,517 +239,495 @@ static int button_mask=0; @end -@interface GodotContentView : NSView -{ - NSTrackingArea* trackingArea; +@interface GodotContentView : NSView { + NSTrackingArea* trackingArea; } - - @end @implementation GodotContentView -+ (void)initialize -{ - if (self == [GodotContentView class]) - { - /* if (_glfw.ns.cursor == nil) - { - NSImage* data = [[NSImage alloc] initWithSize:NSMakeSize(1, 1)]; - _glfw.ns.cursor = [[NSCursor alloc] initWithImage:data - hotSpot:NSZeroPoint]; - [data release]; - }*/ - } ++ (void)initialize { + if (self == [GodotContentView class]) { +/* + if (_glfw.ns.cursor == nil) { + NSImage* data = [[NSImage alloc] initWithSize:NSMakeSize(1, 1)]; + _glfw.ns.cursor = [[NSCursor alloc] initWithImage:data hotSpot:NSZeroPoint]; + [data release]; + } +*/ + } } -- (id)init -{ - self = [super init]; - trackingArea = nil; - [self updateTrackingAreas]; - [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]]; - return self; +- (id)init { + self = [super init]; + trackingArea = nil; + [self updateTrackingAreas]; + [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]]; + return self; } - --(void)dealloc -{ - [trackingArea release]; - [super dealloc]; +-(void)dealloc { + [trackingArea release]; + [super dealloc]; } - (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender { - return NSDragOperationCopy; + return NSDragOperationCopy; } - (NSDragOperation)draggingUpdated:(id)sender { - return NSDragOperationCopy; + return NSDragOperationCopy; } - (BOOL)performDragOperation:(id)sender { + NSPasteboard *pboard = [sender draggingPasteboard]; + NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType]; + Vector files; + for(int i=0;imain_loop->drop_files(files,0); + OS_OSX::singleton->move_window_to_foreground(); + } - Vector files; - for(int i=0;imain_loop->drop_files(files,0); - OS_OSX::singleton->move_window_to_foreground(); - } - - return NO; + return NO; } -- (BOOL)isOpaque -{ - return YES; +- (BOOL)isOpaque { + return YES; } -- (BOOL)canBecomeKeyView -{ - return YES; +- (BOOL)canBecomeKeyView { + return YES; } -- (BOOL)acceptsFirstResponder -{ - return YES; +- (BOOL)acceptsFirstResponder { + return YES; } -- (void)cursorUpdate:(NSEvent *)event -{ +- (void)cursorUpdate:(NSEvent *)event { // setModeCursor(window, window->cursorMode); } -- (void)mouseDown:(NSEvent *)event -{ - +- (void)mouseDown:(NSEvent *)event { //print_line("mouse down:"); button_mask|=BUTTON_MASK_LEFT; InputEvent ev; ev.type=InputEvent::MOUSE_BUTTON; - ev.mouse_button.button_index=BUTTON_LEFT; - ev.mouse_button.pressed=true; - ev.mouse_button.x=mouse_x; - ev.mouse_button.y=mouse_y; - ev.mouse_button.global_x=mouse_x; - ev.mouse_button.global_y=mouse_y; - ev.mouse_button.button_mask=button_mask; + ev.mouse_button.button_index = BUTTON_LEFT; + ev.mouse_button.pressed = true; + ev.mouse_button.x = mouse_x; + ev.mouse_button.y = mouse_y; + ev.mouse_button.global_x = mouse_x; + ev.mouse_button.global_y = mouse_y; + ev.mouse_button.button_mask = button_mask; ev.mouse_button.doubleclick = [event clickCount]==2; ev.mouse_button.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->push_input(ev); - - /* _glfwInputMouseClick(window, - GLFW_MOUSE_BUTTON_LEFT, - GLFW_PRESS, - translateFlags([event modifierFlags]));*/ +/* + _glfwInputMouseClick(window, + GLFW_MOUSE_BUTTON_LEFT, + GLFW_PRESS, + translateFlags([event modifierFlags])); +*/ } -- (void)mouseDragged:(NSEvent *)event -{ - [self mouseMoved:event]; +- (void)mouseDragged:(NSEvent *)event { + [self mouseMoved:event]; } -- (void)mouseUp:(NSEvent *)event -{ - - button_mask&=~BUTTON_MASK_LEFT; +- (void)mouseUp:(NSEvent *)event { + button_mask &= ~BUTTON_MASK_LEFT; InputEvent ev; ev.type=InputEvent::MOUSE_BUTTON; - ev.mouse_button.button_index=BUTTON_LEFT; - ev.mouse_button.pressed=false; - ev.mouse_button.x=mouse_x; - ev.mouse_button.y=mouse_y; - ev.mouse_button.global_x=mouse_x; - ev.mouse_button.global_y=mouse_y; - ev.mouse_button.button_mask=button_mask; + ev.mouse_button.button_index = BUTTON_LEFT; + ev.mouse_button.pressed = false; + ev.mouse_button.x = mouse_x; + ev.mouse_button.y = mouse_y; + ev.mouse_button.global_x = mouse_x; + ev.mouse_button.global_y = mouse_y; + ev.mouse_button.button_mask = button_mask; ev.mouse_button.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->push_input(ev); - /* _glfwInputMouseClick(window, - GLFW_MOUSE_BUTTON_LEFT, - GLFW_RELEASE, - translateFlags([event modifierFlags]));*/ +/* + _glfwInputMouseClick(window, + GLFW_MOUSE_BUTTON_LEFT, + GLFW_RELEASE, + translateFlags([event modifierFlags])); +*/ } -- (void)mouseMoved:(NSEvent *)event -{ +- (void)mouseMoved:(NSEvent *)event { InputEvent ev; ev.type=InputEvent::MOUSE_MOTION; - ev.mouse_motion.button_mask=button_mask; - prev_mouse_x=mouse_x; - prev_mouse_y=mouse_y; + ev.mouse_motion.button_mask = button_mask; + prev_mouse_x = mouse_x; + prev_mouse_y = mouse_y; const NSRect contentRect = [OS_OSX::singleton->window_view frame]; const NSPoint p = [event locationInWindow]; mouse_x = p.x * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]); mouse_y = (contentRect.size.height - p.y) * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]); - ev.mouse_motion.x=mouse_x; - ev.mouse_motion.y=mouse_y; - ev.mouse_motion.global_x=mouse_x; - ev.mouse_motion.global_y=mouse_y; - ev.mouse_motion.relative_x=[event deltaX] * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]); - ev.mouse_motion.relative_y=[event deltaY] * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]); + ev.mouse_motion.x = mouse_x; + ev.mouse_motion.y = mouse_y; + ev.mouse_motion.global_x = mouse_x; + ev.mouse_motion.global_y = mouse_y; + ev.mouse_motion.relative_x = [event deltaX] * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]); + ev.mouse_motion.relative_y = [event deltaY] * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]); ev.mouse_motion.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->input->set_mouse_pos(Point2(mouse_x,mouse_y)); OS_OSX::singleton->push_input(ev); +/* + if (window->cursorMode == GLFW_CURSOR_DISABLED) + _glfwInputCursorMotion(window, [event deltaX], [event deltaY]); + else { + const NSRect contentRect = [window->ns.view frame]; + const NSPoint p = [event locationInWindow]; - /* if (window->cursorMode == GLFW_CURSOR_DISABLED) - _glfwInputCursorMotion(window, [event deltaX], [event deltaY]); - else - { - const NSRect contentRect = [window->ns.view frame]; - const NSPoint p = [event locationInWindow]; - - _glfwInputCursorMotion(window, p.x, contentRect.size.height - p.y); - }*/ + _glfwInputCursorMotion(window, p.x, contentRect.size.height - p.y); + } +*/ } -- (void)rightMouseDown:(NSEvent *)event -{ +- (void)rightMouseDown:(NSEvent *)event { - button_mask|=BUTTON_MASK_RIGHT; + button_mask |= BUTTON_MASK_RIGHT; InputEvent ev; - ev.type=InputEvent::MOUSE_BUTTON; - ev.mouse_button.button_index=BUTTON_RIGHT; - ev.mouse_button.pressed=true; - ev.mouse_button.x=mouse_x; - ev.mouse_button.y=mouse_y; - ev.mouse_button.global_x=mouse_x; - ev.mouse_button.global_y=mouse_y; - ev.mouse_button.button_mask=button_mask; + ev.type = InputEvent::MOUSE_BUTTON; + ev.mouse_button.button_index = BUTTON_RIGHT; + ev.mouse_button.pressed = true; + ev.mouse_button.x = mouse_x; + ev.mouse_button.y = mouse_y; + ev.mouse_button.global_x = mouse_x; + ev.mouse_button.global_y = mouse_y; + ev.mouse_button.button_mask = button_mask; ev.mouse_button.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->push_input(ev); - /* _glfwInputMouseClick(window, - GLFW_MOUSE_BUTTON_RIGHT, - GLFW_PRESS, - translateFlags([event modifierFlags]));*/ +/* + _glfwInputMouseClick(window, + GLFW_MOUSE_BUTTON_RIGHT, + GLFW_PRESS, + translateFlags([event modifierFlags])); +*/ } -- (void)rightMouseDragged:(NSEvent *)event -{ - [self mouseMoved:event]; +- (void)rightMouseDragged:(NSEvent *)event { + [self mouseMoved:event]; } -- (void)rightMouseUp:(NSEvent *)event -{ +- (void)rightMouseUp:(NSEvent *)event { - button_mask&=~BUTTON_MASK_RIGHT; + button_mask &= ~BUTTON_MASK_RIGHT; InputEvent ev; ev.type=InputEvent::MOUSE_BUTTON; - ev.mouse_button.button_index=BUTTON_RIGHT; - ev.mouse_button.pressed=false; - ev.mouse_button.x=mouse_x; - ev.mouse_button.y=mouse_y; - ev.mouse_button.global_x=mouse_x; - ev.mouse_button.global_y=mouse_y; - ev.mouse_button.button_mask=button_mask; + ev.mouse_button.button_index = BUTTON_RIGHT; + ev.mouse_button.pressed = false; + ev.mouse_button.x = mouse_x; + ev.mouse_button.y = mouse_y; + ev.mouse_button.global_x = mouse_x; + ev.mouse_button.global_y = mouse_y; + ev.mouse_button.button_mask = button_mask; ev.mouse_button.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->push_input(ev); - /*_glfwInputMouseClick(window, - GLFW_MOUSE_BUTTON_RIGHT, - GLFW_RELEASE, - translateFlags([event modifierFlags]));*/ +/* + _glfwInputMouseClick(window, + GLFW_MOUSE_BUTTON_RIGHT, + GLFW_RELEASE, + translateFlags([event modifierFlags])); +*/ } -- (void)otherMouseDown:(NSEvent *)event -{ +- (void)otherMouseDown:(NSEvent *)event { if ((int) [event buttonNumber]!=2) return; - button_mask|=BUTTON_MASK_MIDDLE; + button_mask |= BUTTON_MASK_MIDDLE; InputEvent ev; ev.type=InputEvent::MOUSE_BUTTON; - ev.mouse_button.button_index=BUTTON_MIDDLE; - ev.mouse_button.pressed=true; - ev.mouse_button.x=mouse_x; - ev.mouse_button.y=mouse_y; - ev.mouse_button.global_x=mouse_x; - ev.mouse_button.global_y=mouse_y; - ev.mouse_button.button_mask=button_mask; + ev.mouse_button.button_index = BUTTON_MIDDLE; + ev.mouse_button.pressed = true; + ev.mouse_button.x = mouse_x; + ev.mouse_button.y = mouse_y; + ev.mouse_button.global_x = mouse_x; + ev.mouse_button.global_y = mouse_y; + ev.mouse_button.button_mask = button_mask; ev.mouse_button.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->push_input(ev); - /*_glfwInputMouseClick(window, - (int) [event buttonNumber], - GLFW_PRESS, - translateFlags([event modifierFlags]));*/ +/* + _glfwInputMouseClick(window, + (int) [event buttonNumber], + GLFW_PRESS, + translateFlags([event modifierFlags])); +*/ } -- (void)otherMouseDragged:(NSEvent *)event -{ - [self mouseMoved:event]; +- (void)otherMouseDragged:(NSEvent *)event { + [self mouseMoved:event]; } -- (void)otherMouseUp:(NSEvent *)event -{ +- (void)otherMouseUp:(NSEvent *)event { if ((int) [event buttonNumber]!=2) return; - button_mask&=~BUTTON_MASK_MIDDLE; + button_mask &= ~BUTTON_MASK_MIDDLE; InputEvent ev; ev.type=InputEvent::MOUSE_BUTTON; - ev.mouse_button.button_index=BUTTON_MIDDLE; - ev.mouse_button.pressed=false; - ev.mouse_button.x=mouse_x; - ev.mouse_button.y=mouse_y; - ev.mouse_button.global_x=mouse_x; - ev.mouse_button.global_y=mouse_y; - ev.mouse_button.button_mask=button_mask; + ev.mouse_button.button_index = BUTTON_MIDDLE; + ev.mouse_button.pressed = false; + ev.mouse_button.x = mouse_x; + ev.mouse_button.y = mouse_y; + ev.mouse_button.global_x = mouse_x; + ev.mouse_button.global_y = mouse_y; + ev.mouse_button.button_mask = button_mask; ev.mouse_button.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->push_input(ev); - /* _glfwInputMouseClick(window, - (int) [event buttonNumber], - GLFW_RELEASE, - translateFlags([event modifierFlags]));*/ + +/* + _glfwInputMouseClick(window, + (int) [event buttonNumber], + GLFW_RELEASE, + translateFlags([event modifierFlags])); +*/ } -- (void)mouseExited:(NSEvent *)event -{ +- (void)mouseExited:(NSEvent *)event { if (!OS_OSX::singleton) return; if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode!=OS::MOUSE_MODE_CAPTURED) OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT); + if (OS_OSX::singleton->input) OS_OSX::singleton->input->set_mouse_in_window(false); - // _glfwInputCursorEnter(window, GL_FALSE); + + //_glfwInputCursorEnter(window, GL_FALSE); } -- (void)mouseEntered:(NSEvent *)event -{ - // _glfwInputCursorEnter(window, GL_TRUE); +- (void)mouseEntered:(NSEvent *)event { + //_glfwInputCursorEnter(window, GL_TRUE); if (!OS_OSX::singleton) return; + if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode!=OS::MOUSE_MODE_CAPTURED) OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER); + if (OS_OSX::singleton->input) OS_OSX::singleton->input->set_mouse_in_window(true); } -- (void)viewDidChangeBackingProperties -{ - /* const NSRect contentRect = [window->ns.view frame]; - const NSRect fbRect = convertRectToBacking(window, contentRect); +- (void)viewDidChangeBackingProperties { +/* + const NSRect contentRect = [window->ns.view frame]; + const NSRect fbRect = convertRectToBacking(window, contentRect); - _glfwInputFramebufferSize(window, fbRect.size.width, fbRect.size.height);*/ + _glfwInputFramebufferSize(window, fbRect.size.width, fbRect.size.height); +*/ } -- (void)updateTrackingAreas -{ - if (trackingArea != nil) - { - [self removeTrackingArea:trackingArea]; - [trackingArea release]; - } +- (void)updateTrackingAreas { + if (trackingArea != nil) { + [self removeTrackingArea:trackingArea]; + [trackingArea release]; + } - NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | - NSTrackingActiveInKeyWindow | - NSTrackingCursorUpdate | - NSTrackingInVisibleRect; + NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | + NSTrackingActiveInKeyWindow | + NSTrackingCursorUpdate | + NSTrackingInVisibleRect; - trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] - options:options - owner:self - userInfo:nil]; + trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] + options:options + owner:self + userInfo:nil]; - [self addTrackingArea:trackingArea]; - [super updateTrackingAreas]; + [self addTrackingArea:trackingArea]; + [super updateTrackingAreas]; } // Translates a OS X keycode to a Godot keycode // -static int translateKey(unsigned int key) -{ - // Keyboard symbol translation table - static const unsigned int table[128] = - { - /* 00 */ KEY_A, - /* 01 */ KEY_S, - /* 02 */ KEY_D, - /* 03 */ KEY_F, - /* 04 */ KEY_H, - /* 05 */ KEY_G, - /* 06 */ KEY_Z, - /* 07 */ KEY_X, - /* 08 */ KEY_C, - /* 09 */ KEY_V, - /* 0a */ KEY_UNKNOWN, - /* 0b */ KEY_B, - /* 0c */ KEY_Q, - /* 0d */ KEY_W, - /* 0e */ KEY_E, - /* 0f */ KEY_R, - /* 10 */ KEY_Y, - /* 11 */ KEY_T, - /* 12 */ KEY_1, - /* 13 */ KEY_2, - /* 14 */ KEY_3, - /* 15 */ KEY_4, - /* 16 */ KEY_6, - /* 17 */ KEY_5, - /* 18 */ KEY_EQUAL, - /* 19 */ KEY_9, - /* 1a */ KEY_7, - /* 1b */ KEY_MINUS, - /* 1c */ KEY_8, - /* 1d */ KEY_0, - /* 1e */ KEY_BRACERIGHT, - /* 1f */ KEY_O, - /* 20 */ KEY_U, - /* 21 */ KEY_BRACELEFT, - /* 22 */ KEY_I, - /* 23 */ KEY_P, - /* 24 */ KEY_RETURN, - /* 25 */ KEY_L, - /* 26 */ KEY_J, - /* 27 */ KEY_APOSTROPHE, - /* 28 */ KEY_K, - /* 29 */ KEY_SEMICOLON, - /* 2a */ KEY_BACKSLASH, - /* 2b */ KEY_COMMA, - /* 2c */ KEY_SLASH, - /* 2d */ KEY_N, - /* 2e */ KEY_M, - /* 2f */ KEY_PERIOD, - /* 30 */ KEY_TAB, - /* 31 */ KEY_SPACE, - /* 32 */ KEY_QUOTELEFT, - /* 33 */ KEY_BACKSPACE, - /* 34 */ KEY_UNKNOWN, - /* 35 */ KEY_ESCAPE, - /* 36 */ KEY_META, - /* 37 */ KEY_META, - /* 38 */ KEY_SHIFT, - /* 39 */ KEY_CAPSLOCK, - /* 3a */ KEY_ALT, - /* 3b */ KEY_CONTROL, - /* 3c */ KEY_SHIFT, - /* 3d */ KEY_ALT, - /* 3e */ KEY_CONTROL, - /* 3f */ KEY_UNKNOWN, /* Function */ - /* 40 */ KEY_UNKNOWN, - /* 41 */ KEY_KP_PERIOD, - /* 42 */ KEY_UNKNOWN, - /* 43 */ KEY_KP_MULTIPLY, - /* 44 */ KEY_UNKNOWN, - /* 45 */ KEY_KP_ADD, - /* 46 */ KEY_UNKNOWN, - /* 47 */ KEY_NUMLOCK, /* Really KeypadClear... */ - /* 48 */ KEY_UNKNOWN, /* VolumeUp */ - /* 49 */ KEY_UNKNOWN, /* VolumeDown */ - /* 4a */ KEY_UNKNOWN, /* Mute */ - /* 4b */ KEY_KP_DIVIDE, - /* 4c */ KEY_KP_ENTER, - /* 4d */ KEY_UNKNOWN, - /* 4e */ KEY_KP_SUBTRACT, - /* 4f */ KEY_UNKNOWN, - /* 50 */ KEY_UNKNOWN, - /* 51 */ KEY_EQUAL, //wtf equal? - /* 52 */ KEY_KP_0, - /* 53 */ KEY_KP_1, - /* 54 */ KEY_KP_2, - /* 55 */ KEY_KP_3, - /* 56 */ KEY_KP_4, - /* 57 */ KEY_KP_5, - /* 58 */ KEY_KP_6, - /* 59 */ KEY_KP_7, - /* 5a */ KEY_UNKNOWN, - /* 5b */ KEY_KP_8, - /* 5c */ KEY_KP_9, - /* 5d */ KEY_UNKNOWN, - /* 5e */ KEY_UNKNOWN, - /* 5f */ KEY_UNKNOWN, - /* 60 */ KEY_F5, - /* 61 */ KEY_F6, - /* 62 */ KEY_F7, - /* 63 */ KEY_F3, - /* 64 */ KEY_F8, - /* 65 */ KEY_F9, - /* 66 */ KEY_UNKNOWN, - /* 67 */ KEY_F11, - /* 68 */ KEY_UNKNOWN, - /* 69 */ KEY_F13, - /* 6a */ KEY_F16, - /* 6b */ KEY_F14, - /* 6c */ KEY_UNKNOWN, - /* 6d */ KEY_F10, - /* 6e */ KEY_UNKNOWN, - /* 6f */ KEY_F12, - /* 70 */ KEY_UNKNOWN, - /* 71 */ KEY_F15, - /* 72 */ KEY_INSERT, /* Really Help... */ - /* 73 */ KEY_HOME, - /* 74 */ KEY_PAGEUP, - /* 75 */ KEY_DELETE, - /* 76 */ KEY_F4, - /* 77 */ KEY_END, - /* 78 */ KEY_F2, - /* 79 */ KEY_PAGEDOWN, - /* 7a */ KEY_F1, - /* 7b */ KEY_LEFT, - /* 7c */ KEY_RIGHT, - /* 7d */ KEY_DOWN, - /* 7e */ KEY_UP, - /* 7f */ KEY_UNKNOWN, - }; +static int translateKey(unsigned int key) { + // Keyboard symbol translation table + static const unsigned int table[128] = { + /* 00 */ KEY_A, + /* 01 */ KEY_S, + /* 02 */ KEY_D, + /* 03 */ KEY_F, + /* 04 */ KEY_H, + /* 05 */ KEY_G, + /* 06 */ KEY_Z, + /* 07 */ KEY_X, + /* 08 */ KEY_C, + /* 09 */ KEY_V, + /* 0a */ KEY_UNKNOWN, + /* 0b */ KEY_B, + /* 0c */ KEY_Q, + /* 0d */ KEY_W, + /* 0e */ KEY_E, + /* 0f */ KEY_R, + /* 10 */ KEY_Y, + /* 11 */ KEY_T, + /* 12 */ KEY_1, + /* 13 */ KEY_2, + /* 14 */ KEY_3, + /* 15 */ KEY_4, + /* 16 */ KEY_6, + /* 17 */ KEY_5, + /* 18 */ KEY_EQUAL, + /* 19 */ KEY_9, + /* 1a */ KEY_7, + /* 1b */ KEY_MINUS, + /* 1c */ KEY_8, + /* 1d */ KEY_0, + /* 1e */ KEY_BRACERIGHT, + /* 1f */ KEY_O, + /* 20 */ KEY_U, + /* 21 */ KEY_BRACELEFT, + /* 22 */ KEY_I, + /* 23 */ KEY_P, + /* 24 */ KEY_RETURN, + /* 25 */ KEY_L, + /* 26 */ KEY_J, + /* 27 */ KEY_APOSTROPHE, + /* 28 */ KEY_K, + /* 29 */ KEY_SEMICOLON, + /* 2a */ KEY_BACKSLASH, + /* 2b */ KEY_COMMA, + /* 2c */ KEY_SLASH, + /* 2d */ KEY_N, + /* 2e */ KEY_M, + /* 2f */ KEY_PERIOD, + /* 30 */ KEY_TAB, + /* 31 */ KEY_SPACE, + /* 32 */ KEY_QUOTELEFT, + /* 33 */ KEY_BACKSPACE, + /* 34 */ KEY_UNKNOWN, + /* 35 */ KEY_ESCAPE, + /* 36 */ KEY_META, + /* 37 */ KEY_META, + /* 38 */ KEY_SHIFT, + /* 39 */ KEY_CAPSLOCK, + /* 3a */ KEY_ALT, + /* 3b */ KEY_CONTROL, + /* 3c */ KEY_SHIFT, + /* 3d */ KEY_ALT, + /* 3e */ KEY_CONTROL, + /* 3f */ KEY_UNKNOWN, /* Function */ + /* 40 */ KEY_UNKNOWN, + /* 41 */ KEY_KP_PERIOD, + /* 42 */ KEY_UNKNOWN, + /* 43 */ KEY_KP_MULTIPLY, + /* 44 */ KEY_UNKNOWN, + /* 45 */ KEY_KP_ADD, + /* 46 */ KEY_UNKNOWN, + /* 47 */ KEY_NUMLOCK, /* Really KeypadClear... */ + /* 48 */ KEY_UNKNOWN, /* VolumeUp */ + /* 49 */ KEY_UNKNOWN, /* VolumeDown */ + /* 4a */ KEY_UNKNOWN, /* Mute */ + /* 4b */ KEY_KP_DIVIDE, + /* 4c */ KEY_KP_ENTER, + /* 4d */ KEY_UNKNOWN, + /* 4e */ KEY_KP_SUBTRACT, + /* 4f */ KEY_UNKNOWN, + /* 50 */ KEY_UNKNOWN, + /* 51 */ KEY_EQUAL, //wtf equal? + /* 52 */ KEY_KP_0, + /* 53 */ KEY_KP_1, + /* 54 */ KEY_KP_2, + /* 55 */ KEY_KP_3, + /* 56 */ KEY_KP_4, + /* 57 */ KEY_KP_5, + /* 58 */ KEY_KP_6, + /* 59 */ KEY_KP_7, + /* 5a */ KEY_UNKNOWN, + /* 5b */ KEY_KP_8, + /* 5c */ KEY_KP_9, + /* 5d */ KEY_UNKNOWN, + /* 5e */ KEY_UNKNOWN, + /* 5f */ KEY_UNKNOWN, + /* 60 */ KEY_F5, + /* 61 */ KEY_F6, + /* 62 */ KEY_F7, + /* 63 */ KEY_F3, + /* 64 */ KEY_F8, + /* 65 */ KEY_F9, + /* 66 */ KEY_UNKNOWN, + /* 67 */ KEY_F11, + /* 68 */ KEY_UNKNOWN, + /* 69 */ KEY_F13, + /* 6a */ KEY_F16, + /* 6b */ KEY_F14, + /* 6c */ KEY_UNKNOWN, + /* 6d */ KEY_F10, + /* 6e */ KEY_UNKNOWN, + /* 6f */ KEY_F12, + /* 70 */ KEY_UNKNOWN, + /* 71 */ KEY_F15, + /* 72 */ KEY_INSERT, /* Really Help... */ + /* 73 */ KEY_HOME, + /* 74 */ KEY_PAGEUP, + /* 75 */ KEY_DELETE, + /* 76 */ KEY_F4, + /* 77 */ KEY_END, + /* 78 */ KEY_F2, + /* 79 */ KEY_PAGEDOWN, + /* 7a */ KEY_F1, + /* 7b */ KEY_LEFT, + /* 7c */ KEY_RIGHT, + /* 7d */ KEY_DOWN, + /* 7e */ KEY_UP, + /* 7f */ KEY_UNKNOWN, + }; - if (key >= 128) - return KEY_UNKNOWN; + if (key >= 128) + return KEY_UNKNOWN; - return table[key]; + return table[key]; } -- (void)keyDown:(NSEvent *)event -{ - InputEvent ev; - ev.type=InputEvent::KEY; - ev.key.pressed=true; - ev.key.mod=translateFlags([event modifierFlags]); - ev.key.scancode = latin_keyboard_keycode_convert(translateKey([event keyCode])); - ev.key.echo = [event isARepeat]; - NSString* characters = [event characters]; - NSUInteger i, length = [characters length]; +- (void)keyDown:(NSEvent *)event { + InputEvent ev; + ev.type = InputEvent::KEY; + ev.key.pressed = true; + ev.key.mod = translateFlags([event modifierFlags]); + ev.key.scancode = latin_keyboard_keycode_convert(translateKey([event keyCode])); + ev.key.echo = [event isARepeat]; + NSString* characters = [event characters]; + NSUInteger i, length = [characters length]; - if (length>0 && keycode_has_unicode(ev.key.scancode)) { - - - for (i = 0; i < length; i++) { - ev.key.unicode=[characters characterAtIndex:i]; + if (length > 0 && keycode_has_unicode(ev.key.scancode)) { + for (i = 0; i < length; i++) { + ev.key.unicode=[characters characterAtIndex:i]; + OS_OSX::singleton->push_input(ev); + ev.key.scancode=0; + } + } else { OS_OSX::singleton->push_input(ev); - ev.key.scancode=0; } - - } else { - OS_OSX::singleton->push_input(ev); - } } -- (void)flagsChanged:(NSEvent *)event -{ +- (void)flagsChanged:(NSEvent *)event { InputEvent ev; int key = [event keyCode]; int mod = [event modifierFlags]; @@ -814,76 +772,72 @@ static int translateKey(unsigned int key) OS_OSX::singleton->push_input(ev); } -- (void)keyUp:(NSEvent *)event -{ +- (void)keyUp:(NSEvent *)event { InputEvent ev; - ev.type=InputEvent::KEY; - ev.key.pressed=false; - ev.key.mod=translateFlags([event modifierFlags]); + ev.type = InputEvent::KEY; + ev.key.pressed = false; + ev.key.mod = translateFlags([event modifierFlags]); ev.key.scancode = latin_keyboard_keycode_convert(translateKey([event keyCode])); OS_OSX::singleton->push_input(ev); - - /* const int key = translateKey([event keyCode]); - const int mods = translateFlags([event modifierFlags]); - _glfwInputKey(window, key, [event keyCode], GLFW_RELEASE, mods);*/ +/* + const int key = translateKey([event keyCode]); + const int mods = translateFlags([event modifierFlags]); + _glfwInputKey(window, key, [event keyCode], GLFW_RELEASE, mods); +*/ } -- (void)scrollWheel:(NSEvent *)event -{ +- (void)scrollWheel:(NSEvent *)event{ double deltaX, deltaY; #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 - if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6) - { - deltaX = [event scrollingDeltaX]; - deltaY = [event scrollingDeltaY]; + if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6) { + deltaX = [event scrollingDeltaX]; + deltaY = [event scrollingDeltaY]; - if ([event hasPreciseScrollingDeltas]) - { - deltaX *= 0.1; - deltaY *= 0.1; + if ([event hasPreciseScrollingDeltas]) { + deltaX *= 0.1; + deltaY *= 0.1; + } + } else { + deltaX = [event deltaX]; + deltaY = [event deltaY]; } - } - else -#endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/ - { +#else deltaX = [event deltaX]; deltaY = [event deltaY]; - } - +#endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/ if (fabs(deltaY)) { InputEvent ev; ev.type=InputEvent::MOUSE_BUTTON; - ev.mouse_button.button_index=deltaY >0 ? BUTTON_WHEEL_UP : BUTTON_WHEEL_DOWN; - ev.mouse_button.pressed=true; - ev.mouse_button.x=mouse_x; - ev.mouse_button.y=mouse_y; - ev.mouse_button.global_x=mouse_x; - ev.mouse_button.global_y=mouse_y; - ev.mouse_button.button_mask=button_mask; + ev.mouse_button.button_index = deltaY >0 ? BUTTON_WHEEL_UP : BUTTON_WHEEL_DOWN; + ev.mouse_button.pressed = true; + ev.mouse_button.x = mouse_x; + ev.mouse_button.y = mouse_y; + ev.mouse_button.global_x = mouse_x; + ev.mouse_button.global_y = mouse_y; + ev.mouse_button.button_mask = button_mask; OS_OSX::singleton->push_input(ev); - ev.mouse_button.pressed=false; + ev.mouse_button.pressed = false; OS_OSX::singleton->push_input(ev); } if (fabs(deltaX)) { - InputEvent ev; ev.type=InputEvent::MOUSE_BUTTON; - ev.mouse_button.button_index=deltaX < 0 ? BUTTON_WHEEL_RIGHT : BUTTON_WHEEL_LEFT; - ev.mouse_button.pressed=true; - ev.mouse_button.x=mouse_x; - ev.mouse_button.y=mouse_y; - ev.mouse_button.global_x=mouse_x; - ev.mouse_button.global_y=mouse_y; - ev.mouse_button.button_mask=button_mask; + ev.mouse_button.button_index = deltaX < 0 ? BUTTON_WHEEL_RIGHT : BUTTON_WHEEL_LEFT; + ev.mouse_button.pressed = true; + ev.mouse_button.x = mouse_x; + ev.mouse_button.y = mouse_y; + ev.mouse_button.global_x = mouse_x; + ev.mouse_button.global_y = mouse_y; + ev.mouse_button.button_mask = button_mask; OS_OSX::singleton->push_input(ev); - ev.mouse_button.pressed=false; + ev.mouse_button.pressed = false; OS_OSX::singleton->push_input(ev); } } @@ -895,36 +849,32 @@ static int translateKey(unsigned int key) @implementation GodotWindow - -- (BOOL)canBecomeKeyWindow -{ - // Required for NSBorderlessWindowMask windows - return YES; +- (BOOL)canBecomeKeyWindow { + // Required for NSBorderlessWindowMask windows + return YES; } @end int OS_OSX::get_video_driver_count() const { - return 1; } -const char * OS_OSX::get_video_driver_name(int p_driver) const { +const char * OS_OSX::get_video_driver_name(int p_driver) const { return "GLES2"; } OS::VideoMode OS_OSX::get_default_video_mode() const { VideoMode vm; - vm.width=1024; - vm.height=600; - vm.fullscreen=false; - vm.resizable=true; + vm.width = 1024; + vm.height = 600; + vm.fullscreen = false; + vm.resizable = true; return vm; } - void OS_OSX::initialize_core() { OS_Unix::initialize_core(); @@ -952,32 +902,31 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi // Register to be notified on keyboard layout changes CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(), - NULL, keyboardLayoutChanged, - kTISNotifySelectedKeyboardInputSourceChanged, NULL, - CFNotificationSuspensionBehaviorDeliverImmediately); + NULL, keyboardLayoutChanged, + kTISNotifySelectedKeyboardInputSourceChanged, NULL, + CFNotificationSuspensionBehaviorDeliverImmediately); if (is_hidpi_allowed() && [[NSScreen mainScreen] respondsToSelector:@selector(backingScaleFactor)]) { - for (NSScreen *screen in [NSScreen screens]) { - float s = [screen backingScaleFactor]; - if (s > display_scale) { - display_scale=s; - } - } + for (NSScreen *screen in [NSScreen screens]) { + float s = [screen backingScaleFactor]; + if (s > display_scale) { + display_scale=s; + } + } } window_delegate = [[GodotWindowDelegate alloc] init]; - // Don't use accumulation buffer support; it's not accelerated - // Aux buffers probably aren't accelerated either + // Don't use accumulation buffer support; it's not accelerated + // Aux buffers probably aren't accelerated either unsigned int styleMask = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | (p_desired.resizable?NSResizableWindowMask:0); - window_object = [[GodotWindow alloc] - initWithContentRect:NSMakeRect(0, 0, p_desired.width/display_scale, p_desired.height/display_scale) - styleMask:styleMask - backing:NSBackingStoreBuffered - defer:NO]; + initWithContentRect:NSMakeRect(0, 0, p_desired.width/display_scale, p_desired.height/display_scale) + styleMask:styleMask + backing:NSBackingStoreBuffered + defer:NO]; ERR_FAIL_COND( window_object==nil ); @@ -988,8 +937,8 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6 && display_scale>1) { - [window_view setWantsBestResolutionOpenGLSurface:YES]; - //if (current_videomode.resizable) + [window_view setWantsBestResolutionOpenGLSurface:YES]; + //if (current_videomode.resizable) [window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; } #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/ @@ -1011,8 +960,6 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi int colorBits = 32; // Fail if a robustness strategy was requested - - #define ADD_ATTR(x) { attributes[attributeCount++] = x; } #define ADD_ATTR2(x, y) { ADD_ATTR(x); ADD_ATTR(y); } @@ -1029,21 +976,26 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi ADD_ATTR2(NSOpenGLPFAColorSize, colorBits); - /* if (fbconfig->alphaBits > 0) - ADD_ATTR2(NSOpenGLPFAAlphaSize, fbconfig->alphaBits);*/ +/* + if (fbconfig->alphaBits > 0) + ADD_ATTR2(NSOpenGLPFAAlphaSize, fbconfig->alphaBits); +*/ ADD_ATTR2(NSOpenGLPFADepthSize, 24); ADD_ATTR2(NSOpenGLPFAStencilSize, 8); - /*if (fbconfig->stereo) - ADD_ATTR(NSOpenGLPFAStereo);*/ +/* + if (fbconfig->stereo) + ADD_ATTR(NSOpenGLPFAStereo); +*/ - /* if (fbconfig->samples > 0) - { - ADD_ATTR2(NSOpenGLPFASampleBuffers, 1); - ADD_ATTR2(NSOpenGLPFASamples, fbconfig->samples); - }*/ +/* + if (fbconfig->samples > 0) { + ADD_ATTR2(NSOpenGLPFASampleBuffers, 1); + ADD_ATTR2(NSOpenGLPFASamples, fbconfig->samples); + } +*/ // NOTE: All NSOpenGLPixelFormats on the relevant cards support sRGB // frambuffer, so there's no need (and no way) to request it @@ -1056,13 +1008,10 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes]; ERR_FAIL_COND( pixelFormat == nil); - - context = [[NSOpenGLContext alloc] initWithFormat:pixelFormat - shareContext:nil]; + context = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil]; ERR_FAIL_COND(context==nil); - [context setView:window_view]; [context makeCurrentContext]; @@ -1080,19 +1029,16 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi bool use_gl2=p_video_driver!=1; - - AudioDriverManagerSW::add_driver(&audio_driver_osx); - rasterizer = instance_RasterizerGLES2(); visual_server = memnew( VisualServerRaster(rasterizer) ); if (get_render_thread_mode()!=RENDER_THREAD_UNSAFE) { - visual_server =memnew(VisualServerWrapMT(visual_server,get_render_thread_mode()==RENDER_SEPARATE_THREAD)); } + visual_server->init(); visual_server->cursor_set_visible(false, 0); @@ -1115,7 +1061,6 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi spatial_sound_2d_server = memnew( SpatialSound2DServerSW ); spatial_sound_2d_server->init(); - // physics_server = memnew( PhysicsServerSW ); physics_server->init(); //physics_2d_server = memnew( Physics2DServerSW ); @@ -1146,7 +1091,7 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi NSDictionary *description = [[screenArray objectAtIndex: i] deviceDescription]; NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; CGSize displayPhysicalSize = CGDisplayScreenSize( - [[description objectForKey:@"NSScreenNumber"] unsignedIntValue]); + [[description objectForKey:@"NSScreenNumber"] unsignedIntValue]); //printf("width: %i pwidth %i rect width %i\n",int(displayPixelSize.width*displayScale),int(displayPhysicalSize.width*displayScale),int(nsrect.size.width)); int dpi = (displayPixelSize.width * 25.4f / displayPhysicalSize.width)*displayScale; @@ -1156,6 +1101,7 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi }; restore_rect = Rect2(get_window_position(), get_window_size()); } + void OS_OSX::finalize() { CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), NULL, kTISNotifySelectedKeyboardInputSourceChanged, NULL); @@ -1185,13 +1131,11 @@ void OS_OSX::finalize() { memdelete(physics_2d_server); screens.clear(); - - } void OS_OSX::set_main_loop( MainLoop * p_main_loop ) { - main_loop=p_main_loop; + main_loop = p_main_loop; input->set_main_loop(p_main_loop); } @@ -1200,6 +1144,7 @@ void OS_OSX::delete_main_loop() { if (!main_loop) return; + memdelete(main_loop); main_loop=NULL; } @@ -1258,9 +1203,11 @@ void OS_OSX::set_cursor_shape(CursorShape p_shape) { void OS_OSX::set_mouse_show(bool p_show) { } + void OS_OSX::set_mouse_grab(bool p_grab) { } + bool OS_OSX::is_mouse_grab_enabled() const { return mouse_grab; @@ -1268,42 +1215,44 @@ bool OS_OSX::is_mouse_grab_enabled() const { void OS_OSX::warp_mouse_pos(const Point2& p_to) { - //copied from windows impl with osx native calls - if (mouse_mode == MOUSE_MODE_CAPTURED){ - mouse_x = p_to.x; - mouse_y = p_to.y; - } - else{ //set OS position + //copied from windows impl with osx native calls + if (mouse_mode == MOUSE_MODE_CAPTURED){ + mouse_x = p_to.x; + mouse_y = p_to.y; + } else { + //set OS position - /* this code has not been tested, please be a kind soul and fix it if it fails! */ + /* this code has not been tested, please be a kind soul and fix it if it fails! */ - //local point in window coords - NSPoint localPoint = { p_to.x, p_to.y }; + //local point in window coords + NSPoint localPoint = { p_to.x, p_to.y }; - NSPoint pointInWindow = [window_view convertPoint:localPoint toView:nil]; - NSRect pointInWindowRect; - pointInWindowRect.origin = pointInWindow; - NSPoint pointOnScreen = [[window_view window] convertRectToScreen:pointInWindowRect].origin; + NSPoint pointInWindow = [window_view convertPoint:localPoint toView:nil]; + NSRect pointInWindowRect; + pointInWindowRect.origin = pointInWindow; + NSPoint pointOnScreen = [[window_view window] convertRectToScreen:pointInWindowRect].origin; - //point in scren coords - CGPoint lMouseWarpPos = { pointOnScreen.x, pointOnScreen.y}; + //point in scren coords + CGPoint lMouseWarpPos = { pointOnScreen.x, pointOnScreen.y}; - //do the warping - CGEventSourceRef lEventRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState); - CGEventSourceSetLocalEventsSuppressionInterval(lEventRef, 0.0); - CGAssociateMouseAndMouseCursorPosition(false); - CGWarpMouseCursorPosition(lMouseWarpPos); - CGAssociateMouseAndMouseCursorPosition(true); - } + //do the warping + CGEventSourceRef lEventRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState); + CGEventSourceSetLocalEventsSuppressionInterval(lEventRef, 0.0); + CGAssociateMouseAndMouseCursorPosition(false); + CGWarpMouseCursorPosition(lMouseWarpPos); + CGAssociateMouseAndMouseCursorPosition(true); + } } Point2 OS_OSX::get_mouse_pos() const { return Vector2(mouse_x,mouse_y); } + int OS_OSX::get_mouse_button_state() const { return button_mask; } + void OS_OSX::set_window_title(const String& p_title) { [window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]]; @@ -1315,15 +1264,15 @@ void OS_OSX::set_icon(const Image& p_icon) { Image img=p_icon; img.convert(Image::FORMAT_RGBA); NSBitmapImageRep *imgrep= [[[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL - pixelsWide: p_icon.get_width() - pixelsHigh: p_icon.get_height() - bitsPerSample: 8 - samplesPerPixel: 4 - hasAlpha: YES - isPlanar: NO - colorSpaceName: NSDeviceRGBColorSpace - bytesPerRow: p_icon.get_width()*4 - bitsPerPixel: 32] autorelease]; + pixelsWide: p_icon.get_width() + pixelsHigh: p_icon.get_height() + bitsPerSample: 8 + samplesPerPixel: 4 + hasAlpha: YES + isPlanar: NO + colorSpaceName: NSDeviceRGBColorSpace + bytesPerRow: p_icon.get_width()*4 + bitsPerPixel: 32] autorelease]; ERR_FAIL_COND(imgrep==nil); uint8_t *pixels = [imgrep bitmapData]; @@ -1368,18 +1317,17 @@ void OS_OSX::set_clipboard(const String& p_text) { [pasteboard setString:[NSString stringWithUTF8String:p_text.utf8().get_data()] forType:NSStringPboardType]; } + String OS_OSX::get_clipboard() const { NSPasteboard* pasteboard = [NSPasteboard generalPasteboard]; - if (![[pasteboard types] containsObject:NSStringPboardType]) - { + if (![[pasteboard types] containsObject:NSStringPboardType]) { return ""; } NSString* object = [pasteboard stringForType:NSStringPboardType]; - if (!object) - { + if (!object) { return ""; } @@ -1396,6 +1344,7 @@ void OS_OSX::release_rendering_thread() { [NSOpenGLContext clearCurrentContext]; } + void OS_OSX::make_rendering_thread() { [context makeCurrentContext]; @@ -1409,7 +1358,7 @@ Error OS_OSX::shell_open(String p_uri) { } String OS_OSX::get_locale() const { - NSString* preferredLang = [[NSLocale preferredLanguages] objectAtIndex:0]; + NSString* preferredLang = [[NSLocale preferredLanguages] objectAtIndex:0]; return [preferredLang UTF8String]; } @@ -1436,11 +1385,11 @@ OS::VideoMode OS_OSX::get_video_mode(int p_screen) const { return vm; } + void OS_OSX::get_fullscreen_mode_list(List *p_list,int p_screen) const { } - int OS_OSX::get_screen_count() const { return screens.size(); @@ -1508,6 +1457,7 @@ void OS_OSX::set_window_size(const Size2 p_size) { size.y+= [[NSStatusBar systemStatusBar] thickness]; #endif } + NSRect frame = [window_object frame]; [window_object setFrame:NSMakeRect(frame.origin.x, frame.origin.y, size.x, size.y) display:YES]; }; @@ -1636,15 +1586,15 @@ static NSString *createStringForKeys(const CGKeyCode *keyCode, int length) { UniCharCount realLength; err = UCKeyTranslate(keyboardLayout, - keyCode[i], - kUCKeyActionDisplay, - 0, - LMGetKbdType(), - kUCKeyTranslateNoDeadKeysBit, - &keysDown, - sizeof(chars) / sizeof(chars[0]), - &realLength, - chars); + keyCode[i], + kUCKeyActionDisplay, + 0, + LMGetKbdType(), + kUCKeyTranslateNoDeadKeysBit, + &keysDown, + sizeof(chars) / sizeof(chars[0]), + &realLength, + chars); if (err != noErr) { CFRelease(output); @@ -1658,6 +1608,7 @@ static NSString *createStringForKeys(const CGKeyCode *keyCode, int length) { return (NSString *)output; } + OS::LatinKeyboardVariant OS_OSX::get_latin_keyboard_variant() const { static LatinKeyboardVariant layout = LATIN_KEYBOARD_QWERTY; @@ -1707,8 +1658,6 @@ void OS_OSX::process_events() { autoreleasePool = [[NSAutoreleasePool alloc] init]; } - - void OS_OSX::push_input(const InputEvent& p_event) { InputEvent ev=p_event; @@ -1749,29 +1698,29 @@ void OS_OSX::run() { void OS_OSX::set_mouse_mode(MouseMode p_mode) { - if (p_mode==mouse_mode) - return; + if (p_mode == mouse_mode) + return; - if (p_mode==MOUSE_MODE_CAPTURED) { - // Apple Docs state that the display parameter is not used. - // "This parameter is not used. By default, you may pass kCGDirectMainDisplay." - // https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/Quartz_Services_Ref/Reference/reference.html - CGDisplayHideCursor(kCGDirectMainDisplay); - CGAssociateMouseAndMouseCursorPosition(false); - } else if (p_mode==MOUSE_MODE_HIDDEN) { - CGDisplayHideCursor(kCGDirectMainDisplay); - CGAssociateMouseAndMouseCursorPosition(true); - } else { - CGDisplayShowCursor(kCGDirectMainDisplay); - CGAssociateMouseAndMouseCursorPosition(true); - } + if (p_mode == MOUSE_MODE_CAPTURED) { + // Apple Docs state that the display parameter is not used. + // "This parameter is not used. By default, you may pass kCGDirectMainDisplay." + // https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/Quartz_Services_Ref/Reference/reference.html + CGDisplayHideCursor(kCGDirectMainDisplay); + CGAssociateMouseAndMouseCursorPosition(false); + } else if (p_mode == MOUSE_MODE_HIDDEN) { + CGDisplayHideCursor(kCGDirectMainDisplay); + CGAssociateMouseAndMouseCursorPosition(true); + } else { + CGDisplayShowCursor(kCGDirectMainDisplay); + CGAssociateMouseAndMouseCursorPosition(true); + } - mouse_mode=p_mode; + mouse_mode=p_mode; } OS::MouseMode OS_OSX::get_mouse_mode() const { - return mouse_mode; + return mouse_mode; } String OS_OSX::get_joy_guid(int p_device) const { @@ -1782,9 +1731,9 @@ OS_OSX* OS_OSX::singleton=NULL; OS_OSX::OS_OSX() { - mouse_mode=OS::MOUSE_MODE_VISIBLE; - main_loop=NULL; - singleton=this; + mouse_mode = OS::MOUSE_MODE_VISIBLE; + main_loop = NULL; + singleton = this; autoreleasePool = [[NSAutoreleasePool alloc] init]; eventSource = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); @@ -1792,13 +1741,13 @@ OS_OSX::OS_OSX() { CGEventSourceSetLocalEventsSuppressionInterval(eventSource, 0.0); - - /*if (pthread_key_create(&_Godot.nsgl.current, NULL) != 0) - { - _GodotInputError(Godot_PLATFORM_ERROR, - "NSGL: Failed to create context TLS"); - return GL_FALSE; - }*/ +/* + if (pthread_key_create(&_Godot.nsgl.current, NULL) != 0) { + _GodotInputError(Godot_PLATFORM_ERROR, + "NSGL: Failed to create context TLS"); + return GL_FALSE; + } +*/ framework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl")); ERR_FAIL_COND(!framework); @@ -1809,12 +1758,12 @@ OS_OSX::OS_OSX() { // In case we are unbundled, make us a proper UI application [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; - #if 0 +#if 0 // Menu bar setup must go between sharedApplication above and // finishLaunching below, in order to properly emulate the behavior // of NSApplicationMain createMenuBar(); - #endif +#endif [NSApp finishLaunching]; @@ -1822,15 +1771,14 @@ OS_OSX::OS_OSX() { ERR_FAIL_COND(!delegate); [NSApp setDelegate:delegate]; - - last_id=1; - cursor_shape=CURSOR_ARROW; + last_id = 1; + cursor_shape = CURSOR_ARROW; current_screen = 0; maximized = false; minimized = false; - window_size=Vector2(1024,600); + window_size = Vector2(1024,600); zoomed = false; - display_scale=1.0; + display_scale = 1.0; }