diff --git a/misc/hooks/pre-commit-clang-format b/misc/hooks/pre-commit-clang-format index f7620fe2c5a..88c43fc1f50 100755 --- a/misc/hooks/pre-commit-clang-format +++ b/misc/hooks/pre-commit-clang-format @@ -31,7 +31,7 @@ PARSE_EXTS=true # File types to parse. Only effective when PARSE_EXTS is true. # FILE_EXTS=".c .h .cpp .hpp" -FILE_EXTS=".c .h .cpp .hpp .cc .hh .cxx .m" +FILE_EXTS=".c .h .cpp .hpp .cc .hh .cxx .m .mm .inc" # Use pygmentize instead of cat to parse diff with highlighting. # Install it with `pip install pygments` (Linux) or `easy_install Pygments` (Mac) diff --git a/misc/travis/clang-format.sh b/misc/travis/clang-format.sh index 5ecc1b37d8e..741d3bff1b1 100755 --- a/misc/travis/clang-format.sh +++ b/misc/travis/clang-format.sh @@ -11,7 +11,7 @@ else RANGE=HEAD fi -FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -v thirdparty/ | grep -e "\.cpp$" -e "\.h$" -e "\.inc$") +FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -v thirdparty/ | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|m|mm|inc)$") echo "Checking files:\n$FILES" # create a random filename to store our generated patch diff --git a/platform/iphone/app_delegate.mm b/platform/iphone/app_delegate.mm index 22bab1bd94f..cf2c6cc7816 100644 --- a/platform/iphone/app_delegate.mm +++ b/platform/iphone/app_delegate.mm @@ -28,11 +28,11 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #import "app_delegate.h" -#import "gl_view.h" -#include "os_iphone.h" #include "core/globals.h" +#import "gl_view.h" #include "main/main.h" +#include "os_iphone.h" #ifdef MODULE_FACEBOOKSCORER_IOS_ENABLED #include "modules/FacebookScorer_ios/FacebookScorer.h" @@ -45,19 +45,19 @@ #endif #ifdef MODULE_PARSE_ENABLED -#import #import "FBSDKCoreKit/FBSDKCoreKit.h" +#import #endif -#define kFilteringFactor 0.1 -#define kRenderingFrequency 60 -#define kAccelerometerFrequency 100.0 // Hz +#define kFilteringFactor 0.1 +#define kRenderingFrequency 60 +#define kAccelerometerFrequency 100.0 // Hz Error _shell_open(String); void _set_keep_screen_on(bool p_enabled); Error _shell_open(String p_uri) { - NSString* url = [[NSString alloc] initWithUTF8String:p_uri.utf8().get_data()]; + NSString *url = [[NSString alloc] initWithUTF8String:p_uri.utf8().get_data()]; if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]]) return ERR_CANT_OPEN; @@ -77,20 +77,21 @@ void _set_keep_screen_on(bool p_enabled) { @synthesize window; extern int gargc; -extern char** gargv; -extern int iphone_main(int, int, int, char**); +extern char **gargv; +extern int iphone_main(int, int, int, char **); extern void iphone_finish(); CMMotionManager *motionManager; -bool motionInitialised; +bool motionInitialised; -static ViewController* mainViewController = nil; -+ (ViewController*) getViewController { +static ViewController *mainViewController = nil; ++ (ViewController *)getViewController { return mainViewController; } static int frame_count = 0; -- (void)drawView:(GLView*)view; { +- (void)drawView:(GLView *)view; +{ switch (frame_count) { case 0: { @@ -111,7 +112,7 @@ static int frame_count = 0; }; ++frame_count; - NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + 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])); @@ -119,16 +120,16 @@ static int frame_count = 0; 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)]) { + 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 ) { + if (!uuid) { CFUUIDRef cfuuid = CFUUIDCreate(NULL); - uuid = (__bridge_transfer NSString*)CFUUIDCreateString(NULL, cfuuid); + uuid = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, cfuuid); CFRelease(cfuuid); [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"identifierForVendor"]; } @@ -137,7 +138,7 @@ static int frame_count = 0; OSIPhone::get_singleton()->set_unique_ID(String::utf8([uuid UTF8String])); }; break; -/* + /* case 1: { ++frame_count; }; break; @@ -148,31 +149,31 @@ static int frame_count = 0; ++frame_count; // this might be necessary before here - NSDictionary* dict = [[NSBundle mainBundle] infoDictionary]; - for (NSString* key in dict) { - NSObject* value = [dict objectForKey:key]; + 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; + NSString *str = (NSString *)value; String uval = String::utf8([str UTF8String]); - Globals::get_singleton()->set("Info.plist/"+ukey, uval); + Globals::get_singleton()->set("Info.plist/" + ukey, uval); } else if ([value isKindOfClass:[NSNumber class]]) { - NSNumber* n = (NSNumber*)value; + NSNumber *n = (NSNumber *)value; double dval = [n doubleValue]; - Globals::get_singleton()->set("Info.plist/"+ukey, dval); + Globals::get_singleton()->set("Info.plist/" + ukey, dval); }; // do stuff } }; break; -/* + /* case 3: { ++frame_count; } break; @@ -205,7 +206,7 @@ static int frame_count = 0; // [[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 + ///@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]) { @@ -248,7 +249,7 @@ static int frame_count = 0; OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_MEMORY_WARNING); }; -- (void)applicationDidFinishLaunching:(UIApplication*)application { +- (void)applicationDidFinishLaunching:(UIApplication *)application { printf("**************** app delegate init\n"); CGRect rect = [[UIScreen mainScreen] bounds]; @@ -281,8 +282,8 @@ static int frame_count = 0; view_controller.view = glView; window.rootViewController = view_controller; - _set_keep_screen_on(bool(GLOBAL_DEF("display/keep_screen_on",true)) ? YES : NO); - glView.useCADisplayLink = bool(GLOBAL_DEF("display.iOS/use_cadisplaylink",true)) ? YES : NO; + _set_keep_screen_on(bool(GLOBAL_DEF("display/keep_screen_on", true)) ? YES : NO); + glView.useCADisplayLink = bool(GLOBAL_DEF("display.iOS/use_cadisplaylink", true)) ? YES : NO; printf("cadisaplylink: %d", glView.useCADisplayLink); glView.animationInterval = 1.0 / kRenderingFrequency; [glView startAnimation]; @@ -293,8 +294,8 @@ static int frame_count = 0; if (!motionInitialised) { motionManager = [[CMMotionManager alloc] init]; if (motionManager.deviceMotionAvailable) { - motionManager.deviceMotionUpdateInterval = 1.0/70.0; - [motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical]; + motionManager.deviceMotionUpdateInterval = 1.0 / 70.0; + [motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical]; motionInitialised = YES; }; }; @@ -313,11 +314,11 @@ static int frame_count = 0; 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]; @@ -325,12 +326,12 @@ static int frame_count = 0; // 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]]; + advertisingTrackingEnabled:[[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]]; #endif }; -- (void)applicationWillTerminate:(UIApplication*)application { +- (void)applicationWillTerminate:(UIApplication *)application { printf("********************* will terminate\n"); @@ -339,7 +340,7 @@ static int frame_count = 0; [motionManager stopDeviceMotionUpdates]; [motionManager release]; motionManager = nil; - motionInitialised = NO; + motionInitialised = NO; }; iphone_finish(); @@ -365,13 +366,13 @@ static int frame_count = 0; [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"); @@ -399,13 +400,13 @@ static int frame_count = 0; - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { #ifdef MODULE_PARSE_ENABLED NSLog(@"Handling application openURL"); - return [[FBSDKApplicationDelegate sharedInstance] application:application - openURL:url - sourceApplication:sourceApplication - annotation:annotation]; + return [[FBSDKApplicationDelegate sharedInstance] + application:application + openURL:url + sourceApplication:sourceApplication + annotation:annotation]; #endif - #ifdef MODULE_FACEBOOKSCORER_IOS_ENABLED return [[[FacebookScorer sharedInstance] facebook] handleOpenURL:url]; #else diff --git a/platform/iphone/game_center.mm b/platform/iphone/game_center.mm index 5a92b773b10..06db99bf566 100644 --- a/platform/iphone/game_center.mm +++ b/platform/iphone/game_center.mm @@ -28,29 +28,25 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #ifdef GAME_CENTER_ENABLED - #include "game_center.h" #ifdef __IPHONE_9_0 - #import extern "C" { #else - extern "C" { #import - #endif #import "app_delegate.h" }; -GameCenter* GameCenter::instance = NULL; +GameCenter *GameCenter::instance = NULL; void GameCenter::_bind_methods() { - ObjectTypeDB::bind_method(_MD("connect"),&GameCenter::connect); - ObjectTypeDB::bind_method(_MD("is_connected"),&GameCenter::is_connected); + 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); @@ -63,7 +59,6 @@ void GameCenter::_bind_methods() { ObjectTypeDB::bind_method(_MD("pop_pending_event"), &GameCenter::pop_pending_event); }; - Error GameCenter::connect() { //if this class isn't available, game center isn't implemented @@ -72,10 +67,10 @@ Error GameCenter::connect() { return ERR_UNAVAILABLE; } - GKLocalPlayer* player = [GKLocalPlayer localPlayer]; + GKLocalPlayer *player = [GKLocalPlayer localPlayer]; ERR_FAIL_COND_V(![player respondsToSelector:@selector(authenticateHandler)], ERR_UNAVAILABLE); - ViewController *root_controller=(ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController; + ViewController *root_controller = (ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController; ERR_FAIL_COND_V(!root_controller, FAILED); //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. @@ -113,25 +108,26 @@ Error GameCenter::post_score(Variant p_score) { float score = params["score"]; String category = params["category"]; - NSString* cat_str = [[[NSString alloc] initWithUTF8String:category.utf8().get_data()] autorelease]; - GKScore* reporter = [[[GKScore alloc] initWithCategory:cat_str] autorelease]; + NSString *cat_str = [[[NSString alloc] initWithUTF8String:category.utf8().get_data()] autorelease]; + GKScore *reporter = [[[GKScore alloc] initWithCategory:cat_str] autorelease]; reporter.value = 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) { - ret["result"] = "ok"; - } else { - ret["result"] = "error"; - ret["error_code"] = error.code; - ret["error_description"] = [error.localizedDescription UTF8String]; - }; + [GKScore reportScores:@[ reporter ] + withCompletionHandler:^(NSError *error) { + Dictionary ret; + ret["type"] = "post_score"; + if (error == nil) { + ret["result"] = "ok"; + } else { + ret["result"] = "error"; + ret["error_code"] = error.code; + ret["error_description"] = [error.localizedDescription UTF8String]; + }; - pending_events.push_back(ret); - }]; + pending_events.push_back(ret); + }]; return OK; }; @@ -143,8 +139,8 @@ Error GameCenter::award_achievement(Variant p_params) { String name = params["name"]; float progress = params["progress"]; - NSString* name_str = [[[NSString alloc] initWithUTF8String:name.utf8().get_data()] autorelease]; - GKAchievement* achievement = [[[GKAchievement alloc] initWithIdentifier: name_str] autorelease]; + NSString *name_str = [[[NSString alloc] initWithUTF8String:name.utf8().get_data()] autorelease]; + GKAchievement *achievement = [[[GKAchievement alloc] initWithIdentifier:name_str] autorelease]; ERR_FAIL_COND_V(!achievement, FAILED); ERR_FAIL_COND_V([GKAchievement respondsToSelector:@selector(reportAchievements)], ERR_UNAVAILABLE); @@ -155,19 +151,20 @@ Error GameCenter::award_achievement(Variant p_params) { achievement.showsCompletionBanner = params["show_completion_banner"] ? YES : NO; } - [GKAchievement reportAchievements:@[achievement] withCompletionHandler:^(NSError *error) { + [GKAchievement reportAchievements:@[ achievement ] + withCompletionHandler:^(NSError *error) { - Dictionary ret; - ret["type"] = "award_achievement"; - if (error == nil) { - ret["result"] = "ok"; - } else { - ret["result"] = "error"; - ret["error_code"] = error.code; - }; + Dictionary ret; + ret["type"] = "award_achievement"; + if (error == nil) { + ret["result"] = "ok"; + } else { + ret["result"] = "error"; + ret["error_code"] = error.code; + }; - pending_events.push_back(ret); - }]; + pending_events.push_back(ret); + }]; return OK; }; @@ -188,11 +185,11 @@ void GameCenter::request_achievement_descriptions() { Array hidden; Array replayable; - for (int i=0; i<[descriptions count]; i++) { + for (int i = 0; i < [descriptions count]; i++) { - GKAchievementDescription* description = [descriptions objectAtIndex:i]; + GKAchievementDescription *description = [descriptions objectAtIndex:i]; - const char* str = [description.identifier UTF8String]; + const char *str = [description.identifier UTF8String]; names.push_back(String::utf8(str != NULL ? str : "")); str = [description.title UTF8String]; @@ -228,7 +225,6 @@ void GameCenter::request_achievement_descriptions() { }]; }; - void GameCenter::request_achievements() { [GKAchievement loadAchievementsWithCompletionHandler:^(NSArray *achievements, NSError *error) { @@ -240,10 +236,10 @@ void GameCenter::request_achievements() { StringArray names; RealArray percentages; - for (int i=0; i<[achievements count]; i++) { + for (int i = 0; i < [achievements count]; i++) { - GKAchievement* achievement = [achievements objectAtIndex:i]; - const char* str = [achievement.identifier UTF8String]; + GKAchievement *achievement = [achievements objectAtIndex:i]; + const char *str = [achievement.identifier UTF8String]; names.push_back(String::utf8(str != NULL ? str : "")); percentages.push_back(achievement.percentComplete); @@ -263,8 +259,7 @@ void GameCenter::request_achievements() { void GameCenter::reset_achievements() { - [GKAchievement resetAchievementsWithCompletionHandler:^(NSError *error) - { + [GKAchievement resetAchievementsWithCompletionHandler:^(NSError *error) { Dictionary ret; ret["type"] = "reset_achievements"; if (error == nil) { @@ -289,17 +284,13 @@ Error GameCenter::show_game_center(Variant p_params) { String view_name = params["view"]; if (view_name == "default") { view_state = GKGameCenterViewControllerStateDefault; - } - else if (view_name == "leaderboards") { + } else if (view_name == "leaderboards") { view_state = GKGameCenterViewControllerStateLeaderboards; - } - else if (view_name == "achievements") { + } else if (view_name == "achievements") { view_state = GKGameCenterViewControllerStateAchievements; - } - else if (view_name == "challenges") { + } else if (view_name == "challenges") { view_state = GKGameCenterViewControllerStateChallenges; - } - else { + } else { return ERR_INVALID_PARAMETER; } } @@ -307,7 +298,7 @@ Error GameCenter::show_game_center(Variant p_params) { GKGameCenterViewController *controller = [[GKGameCenterViewController alloc] init]; ERR_FAIL_COND_V(!controller, FAILED); - ViewController *root_controller=(ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController; + ViewController *root_controller = (ViewController *)((AppDelegate *)[[UIApplication sharedApplication] delegate]).window.rootViewController; ERR_FAIL_COND_V(!root_controller, FAILED); controller.gameCenterDelegate = root_controller; @@ -316,12 +307,12 @@ Error GameCenter::show_game_center(Variant p_params) { controller.leaderboardIdentifier = nil; if (params.has("leaderboard_name")) { String name = params["leaderboard_name"]; - NSString* name_str = [[[NSString alloc] initWithUTF8String:name.utf8().get_data()] autorelease]; + NSString *name_str = [[[NSString alloc] initWithUTF8String:name.utf8().get_data()] autorelease]; controller.leaderboardIdentifier = name_str; } } - [root_controller presentViewController: controller animated: YES completion:nil]; + [root_controller presentViewController:controller animated:YES completion:nil]; return OK; }; @@ -348,7 +339,7 @@ Variant GameCenter::pop_pending_event() { return front; }; -GameCenter* GameCenter::get_singleton() { +GameCenter *GameCenter::get_singleton() { return instance; }; @@ -358,8 +349,7 @@ GameCenter::GameCenter() { connected = false; }; - -GameCenter::~GameCenter() { +GameCenter::~GameCenter(){ }; diff --git a/platform/iphone/gl_view.mm b/platform/iphone/gl_view.mm old mode 100755 new mode 100644 index fd1857ea624..2f2e33b7738 --- a/platform/iphone/gl_view.mm +++ b/platform/iphone/gl_view.mm @@ -27,15 +27,15 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ +#import "gl_view.h" -#import -#import -#include "os_iphone.h" -#include "core/os/keyboard.h" #include "core/globals.h" +#include "core/os/keyboard.h" +#include "os_iphone.h" #include "servers/audio_server.h" -#import "gl_view.h" +#import +#import /* @interface GLView (private) @@ -48,7 +48,7 @@ int gl_view_base_fb; static String keyboard_text; -static GLView* _instance = NULL; +static GLView *_instance = NULL; static bool video_found_error = false; static bool video_playing = false; @@ -79,21 +79,22 @@ void _hide_keyboard() { bool _play_video(String p_path, float p_volume, String p_audio_track, String p_subtitle_track) { p_path = Globals::get_singleton()->globalize_path(p_path); - NSString* file_path = [[[NSString alloc] initWithUTF8String:p_path.utf8().get_data()] autorelease]; + NSString *file_path = [[[NSString alloc] initWithUTF8String:p_path.utf8().get_data()] autorelease]; _instance.avAsset = [AVAsset assetWithURL:[NSURL fileURLWithPath:file_path]]; - _instance.avPlayerItem =[[AVPlayerItem alloc]initWithAsset:_instance.avAsset]; + _instance.avPlayerItem = [[AVPlayerItem alloc] initWithAsset:_instance.avAsset]; [_instance.avPlayerItem addObserver:_instance forKeyPath:@"status" options:0 context:nil]; - _instance.avPlayer = [[AVPlayer alloc]initWithPlayerItem:_instance.avPlayerItem]; - _instance.avPlayerLayer =[AVPlayerLayer playerLayerWithPlayer:_instance.avPlayer]; + _instance.avPlayer = [[AVPlayer alloc] initWithPlayerItem:_instance.avPlayerItem]; + _instance.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:_instance.avPlayer]; [_instance.avPlayer addObserver:_instance forKeyPath:@"status" options:0 context:nil]; - [[NSNotificationCenter defaultCenter] addObserver:_instance - selector:@selector(playerItemDidReachEnd:) - name:AVPlayerItemDidPlayToEndTimeNotification - object:[_instance.avPlayer currentItem]]; + [[NSNotificationCenter defaultCenter] + addObserver:_instance + selector:@selector(playerItemDidReachEnd:) + name:AVPlayerItemDidPlayToEndTimeNotification + object:[_instance.avPlayer currentItem]]; [_instance.avPlayer addObserver:_instance forKeyPath:@"rate" options:NSKeyValueObservingOptionNew context:0]; @@ -101,11 +102,11 @@ bool _play_video(String p_path, float p_volume, String p_audio_track, String p_s [_instance.layer addSublayer:_instance.avPlayerLayer]; [_instance.avPlayer play]; - AVMediaSelectionGroup *audioGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic: AVMediaCharacteristicAudible]; + AVMediaSelectionGroup *audioGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicAudible]; NSMutableArray *allAudioParams = [NSMutableArray array]; for (id track in audioGroup.options) { - NSString* language = [[track locale] localeIdentifier]; + NSString *language = [[track locale] localeIdentifier]; NSLog(@"subtitle lang: %@", language); if ([language isEqualToString:[NSString stringWithUTF8String:p_audio_track.utf8()]]) { @@ -117,22 +118,22 @@ bool _play_video(String p_path, float p_volume, String p_audio_track, String p_s AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix]; [audioMix setInputParameters:allAudioParams]; - [_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup: audioGroup]; + [_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup:audioGroup]; [_instance.avPlayer.currentItem setAudioMix:audioMix]; break; } } - AVMediaSelectionGroup *subtitlesGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic: AVMediaCharacteristicLegible]; + AVMediaSelectionGroup *subtitlesGroup = [_instance.avAsset mediaSelectionGroupForMediaCharacteristic:AVMediaCharacteristicLegible]; NSArray *useableTracks = [AVMediaSelectionGroup mediaSelectionOptionsFromArray:subtitlesGroup.options withoutMediaCharacteristics:[NSArray arrayWithObject:AVMediaCharacteristicContainsOnlyForcedSubtitles]]; for (id track in useableTracks) { - NSString* language = [[track locale] localeIdentifier]; + 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]; + [_instance.avPlayer.currentItem selectMediaOption:track inMediaSelectionGroup:subtitlesGroup]; break; } } @@ -178,19 +179,19 @@ void _stop_video() { @synthesize animationInterval; static const int max_touches = 8; -static UITouch* touches[max_touches]; +static UITouch *touches[max_touches]; static void init_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:)]; } @@ -295,19 +298,18 @@ 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]; [self createFramebuffer]; [self drawView]; [self drawView]; - } - (BOOL)createFramebuffer { // Generate IDs for a framebuffer object and a color renderbuffer - UIScreen* mainscr = [UIScreen mainScreen]; + UIScreen *mainscr = [UIScreen mainScreen]; printf("******** screen size %i, %i\n", (int)mainscr.currentMode.size.width, (int)mainscr.currentMode.size.height); float minPointSize = MIN(mainscr.bounds.size.width, mainscr.bounds.size.height); float minScreenSize = MIN(mainscr.currentMode.size.width, mainscr.currentMode.size.height); @@ -332,7 +334,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; } @@ -358,7 +360,7 @@ static void clear_touches() { glDeleteRenderbuffersOES(1, &viewRenderbuffer); viewRenderbuffer = 0; - if(depthRenderbuffer) { + if (depthRenderbuffer) { glDeleteRenderbuffersOES(1, &depthRenderbuffer); depthRenderbuffer = 0; } @@ -374,7 +376,7 @@ static void clear_touches() { // Approximate frame rate // assumes device refreshes at 60 fps - int frameInterval = (int) floor(animationInterval * 60.0f); + int frameInterval = (int)floor(animationInterval * 60.0f); displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawView)]; [displayLink setFrameInterval:frameInterval]; @@ -424,13 +426,14 @@ static void clear_touches() { - (void)drawView { if (useCADisplayLink) { // Pause the CADisplayLink to avoid recursion - [displayLink setPaused: YES]; + [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]; + [displayLink setPaused:NO]; } if (!active) { @@ -442,7 +445,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; } @@ -456,18 +459,18 @@ static void clear_touches() { #ifdef DEBUG_ENABLED GLenum err = glGetError(); - if(err) + if (err) NSLog(@"%x error", err); #endif } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { - NSArray* tlist = [[event allTouches] allObjects]; - for (unsigned int i=0; i< [tlist count]; i++) { + NSArray *tlist = [[event allTouches] allObjects]; + for (unsigned int i = 0; i < [tlist count]; i++) { - if ( [touches containsObject:[tlist objectAtIndex:i]] ) { + if ([touches containsObject:[tlist objectAtIndex:i]]) { - UITouch* touch = [tlist objectAtIndex:i]; + UITouch *touch = [tlist objectAtIndex:i]; if (touch.phase != UITouchPhaseBegan) continue; int tid = get_touch_id(touch); @@ -480,12 +483,12 @@ static void clear_touches() { - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { - NSArray* tlist = [[event allTouches] allObjects]; - for (unsigned int i=0; i< [tlist count]; i++) { + NSArray *tlist = [[event allTouches] allObjects]; + for (unsigned int i = 0; i < [tlist count]; i++) { - if ( [touches containsObject:[tlist objectAtIndex:i]] ) { + if ([touches containsObject:[tlist objectAtIndex:i]]) { - UITouch* touch = [tlist objectAtIndex:i]; + UITouch *touch = [tlist objectAtIndex:i]; if (touch.phase != UITouchPhaseMoved) continue; @@ -497,16 +500,15 @@ static void clear_touches() { OSIPhone::get_singleton()->mouse_move(tid, prev_point.x * self.contentScaleFactor, prev_point.y * self.contentScaleFactor, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, first == tid); }; }; - } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { - NSArray* tlist = [[event allTouches] allObjects]; - for (unsigned int i=0; i< [tlist count]; i++) { + NSArray *tlist = [[event allTouches] allObjects]; + for (unsigned int i = 0; i < [tlist count]; i++) { - if ( [touches containsObject:[tlist objectAtIndex:i]] ) { + if ([touches containsObject:[tlist objectAtIndex:i]]) { - UITouch* touch = [tlist objectAtIndex:i]; + UITouch *touch = [tlist objectAtIndex:i]; if (touch.phase != UITouchPhaseEnded) continue; @@ -529,7 +531,6 @@ static void clear_touches() { return YES; }; - - (void)open_keyboard { //keyboard_text = p_existing; [self becomeFirstResponder]; @@ -555,12 +556,11 @@ static void clear_touches() { String character; character.parse_utf8([p_text UTF8String]); keyboard_text = keyboard_text + character; - OSIPhone::get_singleton()->key(character[0] == 10 ? KEY_ENTER : character[0] , true); + OSIPhone::get_singleton()->key(character[0] == 10 ? KEY_ENTER : character[0], true); printf("inserting text with character %i\n", character[0]); }; -- (void)audioRouteChangeListenerCallback:(NSNotification*)notification -{ +- (void)audioRouteChangeListenerCallback:(NSNotification *)notification { printf("*********** route changed!\n"); NSDictionary *interuptionDict = notification.userInfo; @@ -579,8 +579,8 @@ static void clear_touches() { if (_is_video_playing()) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5f * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ - [_instance.avPlayer play]; // NOTE: change this line according your current player implementation - NSLog(@"resumed play"); + [_instance.avPlayer play]; // NOTE: change this line according your current player implementation + NSLog(@"resumed play"); }); }; }; break; @@ -592,23 +592,24 @@ static void clear_touches() { } } - // 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); } init_touches(); - self. multipleTouchEnabled = YES; + self.multipleTouchEnabled = YES; printf("******** adding observer for sound routing changes\n"); - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) - name:AVAudioSessionRouteChangeNotification - object:nil]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(audioRouteChangeListenerCallback:) + name:AVAudioSessionRouteChangeNotification + object:nil]; //self.autoresizesSubviews = YES; //[self setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth]; @@ -628,7 +629,7 @@ static void clear_touches() { - (void)dealloc { [self stopAnimation]; - if([EAGLContext currentContext] == context) { + if ([EAGLContext currentContext] == context) { [EAGLContext setCurrentContext:nil]; } @@ -639,7 +640,8 @@ 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) { @@ -647,9 +649,9 @@ static void clear_touches() { video_found_error = true; } - if(_instance.avPlayer.status == AVPlayerStatusReadyToPlay && - _instance.avPlayerItem.status == AVPlayerItemStatusReadyToPlay && - CMTIME_COMPARE_INLINE(video_current_time, ==, kCMTimeZero)) { + if (_instance.avPlayer.status == AVPlayerStatusReadyToPlay && + _instance.avPlayerItem.status == AVPlayerItemStatusReadyToPlay && + CMTIME_COMPARE_INLINE(video_current_time, ==, kCMTimeZero)) { //NSLog(@"time: %@", video_current_time); @@ -662,8 +664,8 @@ static void clear_touches() { NSLog(@"Player playback rate changed: %.5f", _instance.avPlayer.rate); if (_is_video_playing() && _instance.avPlayer.rate == 0.0 && !_instance.avPlayer.error) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5f * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ - [_instance.avPlayer play]; // NOTE: change this line according your current player implementation - NSLog(@"resumed play"); + [_instance.avPlayer play]; // NOTE: change this line according your current player implementation + NSLog(@"resumed play"); }); NSLog(@" . . . PAUSED (or just started)"); @@ -672,7 +674,7 @@ static void clear_touches() { } - (void)playerItemDidReachEnd:(NSNotification *)notification { - _stop_video(); + _stop_video(); } /* diff --git a/platform/iphone/icloud.mm b/platform/iphone/icloud.mm index cceed574129..01a41533d4d 100644 --- a/platform/iphone/icloud.mm +++ b/platform/iphone/icloud.mm @@ -28,21 +28,21 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #ifdef ICLOUD_ENABLED - #include "icloud.h" #ifndef __IPHONE_9_0 extern "C" { #endif -#import #import "app_delegate.h" +#import + #ifndef __IPHONE_9_0 }; #endif -ICloud* ICloud::instance = NULL; +ICloud *ICloud::instance = NULL; void ICloud::_bind_methods() { ObjectTypeDB::bind_method(_MD("remove_key"), &ICloud::remove_key); @@ -68,18 +68,18 @@ Variant ICloud::pop_pending_event() { return front; }; -ICloud* ICloud::get_singleton() { +ICloud *ICloud::get_singleton() { return instance; }; //convert from apple's abstract type to godot's abstract type.... -Variant nsobject_to_variant(NSObject* object) { +Variant nsobject_to_variant(NSObject *object) { if ([object isKindOfClass:[NSString class]]) { - const char* str = [(NSString*)object UTF8String]; + const char *str = [(NSString *)object UTF8String]; return String::utf8(str != NULL ? str : ""); } else if ([object isKindOfClass:[NSData class]]) { ByteArray ret; - NSData* data = (NSData*)object; + NSData *data = (NSData *)object; if ([data length] > 0) { ret.resize([data length]); { @@ -90,22 +90,21 @@ Variant nsobject_to_variant(NSObject* object) { return ret; } else if ([object isKindOfClass:[NSArray class]]) { Array result; - NSArray* array = (NSArray*)object; + NSArray *array = (NSArray *)object; for (unsigned int i = 0; i < [array count]; ++i) { - NSObject* value = [array objectAtIndex:i]; + NSObject *value = [array objectAtIndex:i]; result.push_back(nsobject_to_variant(value)); } return result; } else if ([object isKindOfClass:[NSDictionary class]]) { Dictionary result; - NSDictionary* dic = (NSDictionary*)object; + NSDictionary *dic = (NSDictionary *)object; - - NSArray* keys = [dic allKeys]; + NSArray *keys = [dic allKeys]; int count = [keys count]; - for (int i=0; i < count; ++i) { - NSObject* k = [ keys objectAtIndex:i]; - NSObject* v = [dic objectForKey:k]; + for (int i = 0; i < count; ++i) { + NSObject *k = [keys objectAtIndex:i]; + NSObject *v = [dic objectForKey:k]; result[nsobject_to_variant(k)] = nsobject_to_variant(v); } @@ -115,20 +114,20 @@ Variant nsobject_to_variant(NSObject* object) { //To avoid errors, we'll cast as broadly as possible, and only return int or float. //bool, char, int, uint, longlong -> int //float, double -> float - NSNumber* num = (NSNumber*)object; - if(strcmp([num objCType], @encode(BOOL)) == 0) { + 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]]) { @@ -145,7 +144,7 @@ Variant nsobject_to_variant(NSObject* object) { } } -NSObject* variant_to_nsobject(Variant v) { +NSObject *variant_to_nsobject(Variant v) { if (v.get_type() == Variant::STRING) { return [[[NSString alloc] initWithUTF8String:((String)v).utf8().get_data()] autorelease]; } else if (v.get_type() == Variant::REAL) { @@ -155,12 +154,12 @@ NSObject* variant_to_nsobject(Variant v) { } else if (v.get_type() == Variant::BOOL) { return [NSNumber numberWithBool:BOOL((bool)v)]; } else if (v.get_type() == Variant::DICTIONARY) { - NSMutableDictionary* result = [[[NSMutableDictionary alloc] init] autorelease]; + NSMutableDictionary *result = [[[NSMutableDictionary alloc] init] autorelease]; Dictionary dic = v; Array keys = dic.keys(); for (unsigned int i = 0; i < keys.size(); ++i) { - NSString* key = [[[NSString alloc] initWithUTF8String:((String)(keys[i])).utf8().get_data()] autorelease]; - NSObject* value = variant_to_nsobject(dic[keys[i]]); + NSString *key = [[[NSString alloc] initWithUTF8String:((String)(keys[i])).utf8().get_data()] autorelease]; + NSObject *value = variant_to_nsobject(dic[keys[i]]); if (key == NULL || value == NULL) { return NULL; @@ -170,10 +169,10 @@ NSObject* variant_to_nsobject(Variant v) { } return result; } else if (v.get_type() == Variant::ARRAY) { - NSMutableArray* result = [[[NSMutableArray alloc] init] autorelease]; + NSMutableArray *result = [[[NSMutableArray alloc] init] autorelease]; Array arr = v; for (unsigned int i = 0; i < arr.size(); ++i) { - NSObject* value = variant_to_nsobject(arr[i]); + NSObject *value = variant_to_nsobject(arr[i]); if (value == NULL) { //trying to add something unsupported to the array. cancel the whole array return NULL; @@ -184,17 +183,16 @@ NSObject* variant_to_nsobject(Variant v) { } 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()]; + NSData *result = [NSData dataWithBytes:r.ptr() length:arr.size()]; return result; } - WARN_PRINT(String("Could not add unsupported type to iCloud: '" + Variant::get_type_name(v.get_type())+"'").utf8().get_data()); + WARN_PRINT(String("Could not add unsupported type to iCloud: '" + Variant::get_type_name(v.get_type()) + "'").utf8().get_data()); return NULL; } - Error ICloud::remove_key(Variant p_param) { String param = p_param; - NSString* key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease]; + NSString *key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease]; NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore]; @@ -217,13 +215,13 @@ Variant ICloud::set_key_values(Variant p_params) { String variant_key = keys[i]; Variant variant_value = params[variant_key]; - NSString* key = [[[NSString alloc] initWithUTF8String:variant_key.utf8().get_data()] autorelease]; + NSString *key = [[[NSString alloc] initWithUTF8String:variant_key.utf8().get_data()] autorelease]; if (key == NULL) { error_keys.push_back(variant_key); continue; } - NSObject* value = variant_to_nsobject(variant_value); + NSObject *value = variant_to_nsobject(variant_value); if (value == NULL) { error_keys.push_back(variant_key); @@ -240,7 +238,7 @@ Variant ICloud::set_key_values(Variant p_params) { Variant ICloud::get_key_value(Variant p_param) { String param = p_param; - NSString* key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease]; + NSString *key = [[[NSString alloc] initWithUTF8String:param.utf8().get_data()] autorelease]; NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore]; if (![[store dictionaryRepresentation] objectForKey:key]) { @@ -255,16 +253,16 @@ Variant ICloud::get_key_value(Variant p_param) { Variant ICloud::get_all_key_values() { Dictionary result; - NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore]; - NSDictionary* store_dictionary = [store dictionaryRepresentation]; + NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore]; + NSDictionary *store_dictionary = [store dictionaryRepresentation]; - NSArray* keys = [store_dictionary allKeys]; + NSArray *keys = [store_dictionary allKeys]; int count = [keys count]; - for (int i=0; i < count; ++i) { - NSString* k = [ keys objectAtIndex:i]; - NSObject* v = [store_dictionary objectForKey:k]; + for (int i = 0; i < count; ++i) { + NSString *k = [keys objectAtIndex:i]; + NSObject *v = [store_dictionary objectForKey:k]; - const char* str = [k UTF8String]; + const char *str = [k UTF8String]; if (str != NULL) { result[String::utf8(str)] = nsobject_to_variant(v); } @@ -303,61 +301,57 @@ ICloud::ICloud() { //connected = false; [ - //[NSNotificationCenter defaultCenter] addObserverForName: @"notify" - [NSNotificationCenter defaultCenter] addObserverForName: NSUbiquitousKeyValueStoreDidChangeExternallyNotification - object: [NSUbiquitousKeyValueStore defaultStore] - queue: nil - usingBlock: ^ (NSNotification * notification) { - NSDictionary* userInfo = [notification userInfo]; - NSInteger change = [[userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey] integerValue]; + //[NSNotificationCenter defaultCenter] addObserverForName: @"notify" + [NSNotificationCenter defaultCenter] + addObserverForName:NSUbiquitousKeyValueStoreDidChangeExternallyNotification + object:[NSUbiquitousKeyValueStore defaultStore] + queue:nil + usingBlock:^(NSNotification *notification) { + NSDictionary *userInfo = [notification userInfo]; + NSInteger change = [[userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey] integerValue]; - Dictionary ret; - ret["type"] = "key_value_changed"; + Dictionary ret; + ret["type"] = "key_value_changed"; - //StringArray result_keys; - //Array result_values; - Dictionary keyValues; - String reason = ""; + //StringArray result_keys; + //Array result_values; + Dictionary keyValues; + String reason = ""; - if (change == NSUbiquitousKeyValueStoreServerChange) { - reason = "server"; - } else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) { - reason = "initial_sync"; - } else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) { - reason = "quota_violation"; - } else if (change == NSUbiquitousKeyValueStoreAccountChange) { - reason = "account"; - } + if (change == NSUbiquitousKeyValueStoreServerChange) { + reason = "server"; + } else if (change == NSUbiquitousKeyValueStoreInitialSyncChange) { + reason = "initial_sync"; + } else if (change == NSUbiquitousKeyValueStoreQuotaViolationChange) { + reason = "quota_violation"; + } else if (change == NSUbiquitousKeyValueStoreAccountChange) { + reason = "account"; + } - ret["reason"] = reason; + ret["reason"] = reason; + NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore]; - NSUbiquitousKeyValueStore *store = [NSUbiquitousKeyValueStore defaultStore]; + NSArray *keys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey]; + for (NSString *key in keys) { + const char *str = [key UTF8String]; + if (str == NULL) { + continue; + } - NSArray * keys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey]; - for (NSString* key in keys) { - const char* str = [key UTF8String]; - if (str == NULL) { - continue; - } + NSObject *object = [store objectForKey:key]; - NSObject* object = [store objectForKey:key]; + //figure out what kind of object it is + Variant value = nsobject_to_variant(object); - //figure out what kind of object it is - Variant value = nsobject_to_variant(object); + keyValues[String::utf8(str)] = value; + } - keyValues[String::utf8(str)] = value; - } - - ret["changed_values"] = keyValues; - pending_events.push_back(ret); - } - ]; + ret["changed_values"] = keyValues; + pending_events.push_back(ret); + }]; } - -ICloud::~ICloud() { - -}; +ICloud::~ICloud(){}; #endif diff --git a/platform/iphone/in_app_store.mm b/platform/iphone/in_app_store.mm index a1df6f3ca1a..06afaa6fe13 100644 --- a/platform/iphone/in_app_store.mm +++ b/platform/iphone/in_app_store.mm @@ -28,23 +28,22 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #ifdef STOREKIT_ENABLED +#include "in_app_store.h" #ifdef MODULE_FUSEBOXX_ENABLED #import "modules/fuseboxx/ios/FuseSDK.h" #endif -#include "in_app_store.h" - extern "C" { - #import - #import +#import +#import }; bool auto_finish_transactions = true; -NSMutableDictionary* pending_transactions = [NSMutableDictionary dictionary]; +NSMutableDictionary *pending_transactions = [NSMutableDictionary dictionary]; @interface SKProduct (LocalizedPrice) -@property (nonatomic, readonly) NSString *localizedPrice; +@property(nonatomic, readonly) NSString *localizedPrice; @end //----------------------------------// @@ -62,30 +61,28 @@ NSMutableDictionary* pending_transactions = [NSMutableDictionary dictionary]; } @end - -InAppStore* InAppStore::instance = NULL; +InAppStore *InAppStore::instance = NULL; void InAppStore::_bind_methods() { - ObjectTypeDB::bind_method(_MD("request_product_info"),&InAppStore::request_product_info); - ObjectTypeDB::bind_method(_MD("purchase"),&InAppStore::purchase); + ObjectTypeDB::bind_method(_MD("request_product_info"), &InAppStore::request_product_info); + ObjectTypeDB::bind_method(_MD("purchase"), &InAppStore::purchase); - ObjectTypeDB::bind_method(_MD("get_pending_event_count"),&InAppStore::get_pending_event_count); - ObjectTypeDB::bind_method(_MD("pop_pending_event"),&InAppStore::pop_pending_event); - ObjectTypeDB::bind_method(_MD("finish_transaction"),&InAppStore::finish_transaction); - ObjectTypeDB::bind_method(_MD("set_auto_finish_transaction"),&InAppStore::set_auto_finish_transaction); + ObjectTypeDB::bind_method(_MD("get_pending_event_count"), &InAppStore::get_pending_event_count); + ObjectTypeDB::bind_method(_MD("pop_pending_event"), &InAppStore::pop_pending_event); + ObjectTypeDB::bind_method(_MD("finish_transaction"), &InAppStore::finish_transaction); + ObjectTypeDB::bind_method(_MD("set_auto_finish_transaction"), &InAppStore::set_auto_finish_transaction); }; -@interface ProductsDelegate : NSObject { - +@interface ProductsDelegate : NSObject { }; @end @implementation ProductsDelegate -- (void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response { +- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { - NSArray* products = response.products; + NSArray *products = response.products; Dictionary ret; ret["type"] = "product_info"; ret["result"] = "ok"; @@ -95,11 +92,11 @@ void InAppStore::_bind_methods() { StringArray ids; StringArray localized_prices; - for (int i=0; i<[products count]; i++) { + for (int i = 0; i < [products count]; i++) { - SKProduct* product = [products objectAtIndex:i]; + SKProduct *product = [products objectAtIndex:i]; - const char* str = [product.localizedTitle UTF8String]; + const char *str = [product.localizedTitle UTF8String]; titles.push_back(String::utf8(str != NULL ? str : "")); str = [product.localizedDescription UTF8String]; @@ -116,7 +113,7 @@ void InAppStore::_bind_methods() { StringArray invalid_ids; - for (NSString* ipid in response.invalidProductIdentifiers) { + for (NSString *ipid in response.invalidProductIdentifiers) { invalid_ids.push_back(String::utf8([ipid UTF8String])); }; @@ -137,15 +134,15 @@ Error InAppStore::request_product_info(Variant p_params) { StringArray pids = params["product_ids"]; printf("************ request product info! %i\n", pids.size()); - NSMutableArray* array = [[[NSMutableArray alloc] initWithCapacity:pids.size()] autorelease]; - for (int i=0; i { - +@interface TransObserver : NSObject { }; @end @implementation TransObserver -- (void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray*) transactions { +- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions { printf("transactions updated!\n"); - for (SKPaymentTransaction* transaction in transactions) { + for (SKPaymentTransaction *transaction in transactions) { switch (transaction.transactionState) { case SKPaymentTransactionStatePurchased: { @@ -179,10 +175,10 @@ Error InAppStore::request_product_info(Variant p_params) { ret["product_id"] = pid; ret["transaction_id"] = transactionId; - NSData* receipt = nil; + 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]; @@ -207,7 +203,7 @@ Error InAppStore::request_product_info(Variant p_params) { receipt = transaction.transactionReceipt; } - NSString* receipt_to_send = nil; + NSString *receipt_to_send = nil; if (receipt != nil) { receipt_to_send = [receipt description]; } @@ -218,16 +214,16 @@ Error InAppStore::request_product_info(Variant p_params) { InAppStore::get_singleton()->_post_event(ret); - if (auto_finish_transactions){ + if (auto_finish_transactions) { [[SKPaymentQueue defaultQueue] finishTransaction:transaction]; } else { - [pending_transactions setObject:transaction forKey:transaction.payment.productIdentifier]; + [pending_transactions setObject:transaction forKey:transaction.payment.productIdentifier]; } - #ifdef MODULE_FUSEBOXX_ENABLED +#ifdef MODULE_FUSEBOXX_ENABLED printf("Registering transaction on Fuseboxx!\n"); - [FuseSDK registerInAppPurchase: transaction]; - #endif + [FuseSDK registerInAppPurchase:transaction]; +#endif }; break; case SKPaymentTransactionStateFailed: { printf("status transaction failed!\n"); @@ -255,7 +251,6 @@ Error InAppStore::request_product_info(Variant p_params) { @end - Error InAppStore::purchase(Variant p_params) { ERR_FAIL_COND_V(![SKPaymentQueue canMakePayments], ERR_UNAVAILABLE); @@ -268,14 +263,13 @@ Error InAppStore::purchase(Variant p_params) { NSString *pid = [[[NSString alloc] initWithUTF8String:String(params["product_id"]).utf8().get_data()] autorelease]; SKPayment *payment = [SKPayment paymentWithProductIdentifier:pid]; - SKPaymentQueue* defq = [SKPaymentQueue defaultQueue]; + SKPaymentQueue *defq = [SKPaymentQueue defaultQueue]; [defq addPayment:payment]; printf("purchase sent!\n"); return OK; }; - int InAppStore::get_pending_event_count() { return pending_events.size(); }; @@ -295,13 +289,13 @@ void InAppStore::_post_event(Variant p_event) { void InAppStore::_record_purchase(String product_id) { - String skey = "purchased/"+product_id; - NSString* key = [[[NSString alloc] initWithUTF8String:skey.utf8().get_data()] autorelease]; + String skey = "purchased/" + product_id; + NSString *key = [[[NSString alloc] initWithUTF8String:skey.utf8().get_data()] autorelease]; [[NSUserDefaults standardUserDefaults] setBool:YES forKey:key]; [[NSUserDefaults standardUserDefaults] synchronize]; }; -InAppStore* InAppStore::get_singleton() { +InAppStore *InAppStore::get_singleton() { return instance; }; @@ -311,13 +305,13 @@ InAppStore::InAppStore() { instance = this; auto_finish_transactions = false; - TransObserver* observer = [[TransObserver alloc] init]; + 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]; +void InAppStore::finish_transaction(String product_id) { + NSString *prod_id = [NSString stringWithCString:product_id.utf8().get_data() encoding:NSUTF8StringEncoding]; if ([pending_transactions objectForKey:prod_id]) { [[SKPaymentQueue defaultQueue] finishTransaction:[pending_transactions objectForKey:prod_id]]; @@ -325,13 +319,12 @@ void InAppStore::finish_transaction(String product_id){ } }; -void InAppStore::set_auto_finish_transaction(bool b){ - auto_finish_transactions = b; +void InAppStore::set_auto_finish_transaction(bool b) { + auto_finish_transactions = b; } -InAppStore::~InAppStore() { +InAppStore::~InAppStore(){ }; - #endif diff --git a/platform/iphone/ios.mm b/platform/iphone/ios.mm index 3f24fab3f45..2b2680f7d1f 100644 --- a/platform/iphone/ios.mm +++ b/platform/iphone/ios.mm @@ -33,7 +33,7 @@ void iOS::_bind_methods() { - ObjectTypeDB::bind_method(_MD("get_rate_url","app_id"),&iOS::get_rate_url); + ObjectTypeDB::bind_method(_MD("get_rate_url", "app_id"), &iOS::get_rate_url); }; String iOS::get_rate_url(int p_app_id) const { @@ -48,7 +48,7 @@ String iOS::get_rate_url(int p_app_id) const { // 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 + // iOS 8 needs a different templateReviewURL also @see https://github.com/arashpayan/appirater/issues/182 ret = templ_iOS8; } @@ -59,4 +59,4 @@ String iOS::get_rate_url(int p_app_id) const { return ret; }; -iOS::iOS() {}; +iOS::iOS(){}; diff --git a/platform/iphone/main.m b/platform/iphone/main.m index cdcbacbd4fb..8bb446b0964 100644 --- a/platform/iphone/main.m +++ b/platform/iphone/main.m @@ -27,12 +27,12 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#import #import "app_delegate.h" +#import #include int gargc; -char** gargv; +char **gargv; int main(int argc, char *argv[]) { printf("*********** main.m\n"); @@ -40,11 +40,10 @@ int main(int argc, char *argv[]) { gargv = argv; NSAutoreleasePool *pool = [NSAutoreleasePool new]; - AppDelegate* app = [AppDelegate alloc]; + AppDelegate *app = [AppDelegate alloc]; printf("running app main\n"); UIApplicationMain(argc, argv, nil, @"AppDelegate"); printf("main done, pool release\n"); [pool release]; return 0; } - diff --git a/platform/iphone/view_controller.mm b/platform/iphone/view_controller.mm index f7fd201e044..574598e1d34 100644 --- a/platform/iphone/view_controller.mm +++ b/platform/iphone/view_controller.mm @@ -33,45 +33,44 @@ 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) { - - 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; +int add_path(int p_argc, char **p_args) { + NSString *str = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_path"]; + if (!str) return p_argc; - }; - int add_cmdline(int p_argc, char** p_args) { - - NSArray* arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_cmdline"]; - if (!arr) - return p_argc; - - for (int i=0; i < [arr count]; i++) { - - NSString* str = [arr objectAtIndex:i]; - if (!str) - continue; - [str retain]; // @todo delete these at some point - p_args[p_argc++] = (char*)[str cString]; - }; - - p_args[p_argc] = NULL; - - return p_argc; - }; + 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]; + if (!str) + continue; + [str retain]; // @todo delete these at some point + p_args[p_argc++] = (char *)[str cString]; + }; + + p_args[p_argc] = NULL; + + return p_argc; +}; +}; // extern "C" + @interface ViewController () @end @@ -85,11 +84,11 @@ extern "C" { - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)p_orientation { - if (/*OSIPhone::get_singleton() == NULL*/TRUE) { + if (/*OSIPhone::get_singleton() == NULL*/ TRUE) { printf("checking on info.plist\n"); - NSArray* arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"]; - switch(p_orientation) { + NSArray *arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"]; + switch (p_orientation) { case UIInterfaceOrientationLandscapeLeft: return [arr indexOfObject:@"UIInterfaceOrientationLandscapeLeft"] != NSNotFound ? YES : NO; @@ -109,19 +108,19 @@ extern "C" { }; uint8_t supported = OSIPhone::get_singleton()->get_orientations(); - switch(p_orientation) { + 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]; diff --git a/platform/osx/dir_access_osx.mm b/platform/osx/dir_access_osx.mm index 931629e5c13..37ba0e6b198 100644 --- a/platform/osx/dir_access_osx.mm +++ b/platform/osx/dir_access_osx.mm @@ -35,17 +35,14 @@ #include - -String DirAccessOSX::fix_unicode_name(const char* p_name) const { +String DirAccessOSX::fix_unicode_name(const char *p_name) const { String fname; - NSString* nsstr = [[NSString stringWithUTF8String: p_name] precomposedStringWithCanonicalMapping]; + NSString *nsstr = [[NSString stringWithUTF8String:p_name] precomposedStringWithCanonicalMapping]; fname.parse_utf8([nsstr UTF8String]); return fname; } - - #endif //posix_enabled diff --git a/platform/osx/godot_main_osx.mm b/platform/osx/godot_main_osx.mm index c883d68d0be..26c156220a1 100644 --- a/platform/osx/godot_main_osx.mm +++ b/platform/osx/godot_main_osx.mm @@ -27,26 +27,24 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "os_osx.h" #include "main/main.h" +#include "os_osx.h" + #include #include -//#define main godot_main - -int main(int argc, char** argv) { +int main(int argc, char **argv) { int first_arg = 1; - const char* dbg_arg = "-NSDocumentRevisionsDebugMode"; + const char *dbg_arg = "-NSDocumentRevisionsDebugMode"; printf("arguments\n"); for (int i = 0; i < argc; i++) { if (strcmp(dbg_arg, argv[i]) == 0) - first_arg = i+2; + first_arg = i + 2; printf("%i: %s\n", i, argv[i]); }; - if (argc >= 1 && argv[0][0] == '/') { //potentially launched from finder int len = strlen(argv[0]); @@ -54,22 +52,21 @@ int main(int argc, char** argv) { if (argv[0][len] == '/') break; } if (len >= 0) { - char *path = (char *)malloc(len+1); + char *path = (char *)malloc(len + 1); memcpy(path, argv[0], len); path[len] = 0; - char *pathinfo = (char*)malloc(strlen(path) + strlen("/../Info.plist")+1); - //in real code you would check for errors in malloc here + 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); chdir(path); chdir("../Resources"); //data.pck, or just the files are here - } free(path); @@ -79,9 +76,8 @@ int main(int argc, char** argv) { OS_OSX os; - - Error err = Main::setup(argv[0], argc-first_arg, &argv[first_arg]); - if (err!=OK) + Error err = Main::setup(argv[0], argc - first_arg, &argv[first_arg]); + if (err != OK) return 255; if (Main::start()) diff --git a/platform/osx/godot_osx.mm b/platform/osx/godot_osx.mm index 3aecac5c87c..626406ad1d3 100644 --- a/platform/osx/godot_osx.mm +++ b/platform/osx/godot_osx.mm @@ -27,30 +27,30 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ +#include "godot_osx.h" + #include /* for MAXPATHLEN */ #include -#include "godot_osx.h" /* For some reaon, Apple removed setAppleMenu from the headers in 10.4, but the method still is there and works. To avoid warnings, we declare it ourselves here. */ -@interface NSApplication() +@interface NSApplication () - (void)setAppleMenu:(NSMenu *)menu; @end -static int global_argc; -static char **global_argv; -static BOOL gCalledAppMainline = FALSE; +static int global_argc; +static char **global_argv; +static BOOL gCalledAppMainline = FALSE; -static NSString *getApplicationName(void) -{ +static NSString *getApplicationName(void) { const NSDictionary *dict; NSString *appName = 0; /* Determine the application name */ dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); if (dict) - appName = [dict objectForKey: @"CFBundleName"]; + appName = [dict objectForKey:@"CFBundleName"]; if (![appName length]) appName = [[NSProcessInfo processInfo] processName]; @@ -61,8 +61,7 @@ static NSString *getApplicationName(void) /* The main class of the application, the application's delegate */ @implementation GodotMain -static void setApplicationMenu(void) -{ +static void setApplicationMenu(void) { /* warning: this code is very odd */ NSMenu *appleMenu; NSMenuItem *menuItem; @@ -82,7 +81,7 @@ static void setApplicationMenu(void) [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; - [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; + [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask | NSCommandKeyMask)]; [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; @@ -91,7 +90,6 @@ static void setApplicationMenu(void) 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]; @@ -106,11 +104,10 @@ static void setApplicationMenu(void) } /* Create a window menu */ -static void setupWindowMenu(void) -{ - NSMenu *windowMenu; - NSMenuItem *windowMenuItem; - NSMenuItem *menuItem; +static void setupWindowMenu(void) { + NSMenu *windowMenu; + NSMenuItem *windowMenuItem; + NSMenuItem *menuItem; windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; @@ -133,10 +130,9 @@ static void setupWindowMenu(void) } /* Replacement for NSApplicationMain */ -static void CustomApplicationMain (int argc, char **argv) -{ - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - GodotMain *main; +static void CustomApplicationMain(int argc, char **argv) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + GodotMain *main; /* Ensure the application object is initialised */ [NSApplication sharedApplication]; @@ -156,11 +152,10 @@ static void CustomApplicationMain (int argc, char **argv) [pool release]; } -extern int godot_main(int argc, char** argv); +extern int godot_main(int argc, char **argv); /* Called when the internal event loop has just started running */ -- (void) applicationDidFinishLaunching: (NSNotification *) note -{ +- (void)applicationDidFinishLaunching:(NSNotification *)note { int status; /* Hand off to main application code */ @@ -176,40 +171,38 @@ extern int godot_main(int argc, char** argv); #undef main #endif -int main (int argc, char **argv) -{ +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; + 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]; + 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); + CustomApplicationMain(argc, argv); return 0; } - diff --git a/platform/osx/os_osx.mm b/platform/osx/os_osx.mm index 043b5c0ffc2..956b0e68483 100644 --- a/platform/osx/os_osx.mm +++ b/platform/osx/os_osx.mm @@ -27,34 +27,33 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#import - -#include -#include -#include -#include -#include - -#include "sem_osx.h" -#include "servers/visual/visual_server_raster.h" -//#include "drivers/opengl/rasterizer_gl.h" -//#include "drivers/gles2/rasterizer_gles2.h" #include "os_osx.h" -#include -#include -#include "print_string.h" -#include "servers/physics/physics_server_sw.h" + +#include "dir_access_osx.h" #include "drivers/gles2/rasterizer_instance_gles2.h" -#include "servers/visual/visual_server_wrap_mt.h" #include "main/main.h" #include "os/keyboard.h" -#include "dir_access_osx.h" +#include "print_string.h" +#include "sem_osx.h" +#include "servers/physics/physics_server_sw.h" +#include "servers/visual/visual_server_raster.h" +#include "servers/visual/visual_server_wrap_mt.h" + +#include +#import +#include +#include +#include +#include -#include -#include #include -#include #include +#include +#include +#include +#include +#include + //uses portions of glfw //======================================================================== @@ -92,7 +91,6 @@ static NSRect convertRectToBacking(NSRect contentRect) { else #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/ return contentRect; - } static InputModifierState translateFlags(NSUInteger flags) { @@ -112,7 +110,6 @@ static int prev_mouse_x = 0; static int prev_mouse_y = 0; static int button_mask = 0; - @interface GodotApplication : NSApplication @end @@ -143,7 +140,7 @@ static int button_mask = 0; } - (void)applicationDidHide:(NSNotification *)notification { -/* + /* _Godotwindow* window; for (window = _Godot.windowListHead; window; window = window->next) @@ -152,7 +149,7 @@ static int button_mask = 0; } - (void)applicationDidUnhide:(NSNotification *)notification { -/* + /* _Godotwindow* window; for (window = _Godot.windowListHead; window; window = window->next) @@ -163,7 +160,7 @@ static int button_mask = 0; */ } -- (void)applicationDidChangeScreenParameters:(NSNotification *) notification { +- (void)applicationDidChangeScreenParameters:(NSNotification *)notification { //_GodotInputMonitorChange(); } @@ -188,10 +185,10 @@ static int button_mask = 0; [OS_OSX::singleton->context update]; const NSRect contentRect = [OS_OSX::singleton->window_view frame]; - const NSRect fbRect = contentRect;//convertRectToBacking(contentRect); + 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; + 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); @@ -226,13 +223,13 @@ static int button_mask = 0; 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); @@ -241,7 +238,7 @@ static int button_mask = 0; @end @interface GodotContentView : NSView { - NSTrackingArea* trackingArea; + NSTrackingArea *trackingArea; } @end @@ -250,7 +247,7 @@ static int button_mask = 0; + (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]; @@ -268,12 +265,12 @@ static int button_mask = 0; return self; } --(void)dealloc { +- (void)dealloc { [trackingArea release]; [super dealloc]; } -- (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)sender { +- (NSDragOperation)draggingEntered:(id)sender { return NSDragOperationCopy; } @@ -286,7 +283,7 @@ static int button_mask = 0; NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType]; Vector files; - for(int i=0;imain_loop->drop_files(files,0); + OS_OSX::singleton->main_loop->drop_files(files, 0); OS_OSX::singleton->move_window_to_foreground(); } return NO; } - - (BOOL)isOpaque { return YES; } @@ -317,14 +313,14 @@ static int button_mask = 0; } - (void)cursorUpdate:(NSEvent *)event { - // setModeCursor(window, window->cursorMode); + //setModeCursor(window, window->cursorMode); } - (void)mouseDown:(NSEvent *)event { //print_line("mouse down:"); - button_mask|=BUTTON_MASK_LEFT; + button_mask |= BUTTON_MASK_LEFT; InputEvent ev; - ev.type=InputEvent::MOUSE_BUTTON; + ev.type = InputEvent::MOUSE_BUTTON; ev.mouse_button.button_index = BUTTON_LEFT; ev.mouse_button.pressed = true; ev.mouse_button.x = mouse_x; @@ -332,11 +328,11 @@ static int button_mask = 0; 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.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, @@ -345,13 +341,13 @@ static int button_mask = 0; } - (void)mouseDragged:(NSEvent *)event { - [self mouseMoved:event]; + [self mouseMoved:event]; } - (void)mouseUp:(NSEvent *)event { button_mask &= ~BUTTON_MASK_LEFT; InputEvent ev; - ev.type=InputEvent::MOUSE_BUTTON; + ev.type = InputEvent::MOUSE_BUTTON; ev.mouse_button.button_index = BUTTON_LEFT; ev.mouse_button.pressed = false; ev.mouse_button.x = mouse_x; @@ -362,7 +358,7 @@ static int button_mask = 0; ev.mouse_button.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->push_input(ev); -/* + /* _glfwInputMouseClick(window, GLFW_MOUSE_BUTTON_LEFT, GLFW_RELEASE, @@ -373,7 +369,7 @@ static int button_mask = 0; - (void)mouseMoved:(NSEvent *)event { InputEvent ev; - ev.type=InputEvent::MOUSE_MOTION; + ev.type = InputEvent::MOUSE_MOTION; ev.mouse_motion.button_mask = button_mask; prev_mouse_x = mouse_x; prev_mouse_y = mouse_y; @@ -389,10 +385,10 @@ static int button_mask = 0; 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->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 { @@ -419,7 +415,7 @@ static int button_mask = 0; ev.mouse_button.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->push_input(ev); -/* + /* _glfwInputMouseClick(window, GLFW_MOUSE_BUTTON_RIGHT, GLFW_PRESS, @@ -435,7 +431,7 @@ static int button_mask = 0; button_mask &= ~BUTTON_MASK_RIGHT; InputEvent ev; - ev.type=InputEvent::MOUSE_BUTTON; + ev.type = InputEvent::MOUSE_BUTTON; ev.mouse_button.button_index = BUTTON_RIGHT; ev.mouse_button.pressed = false; ev.mouse_button.x = mouse_x; @@ -446,7 +442,7 @@ static int button_mask = 0; ev.mouse_button.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->push_input(ev); -/* + /* _glfwInputMouseClick(window, GLFW_MOUSE_BUTTON_RIGHT, GLFW_RELEASE, @@ -456,12 +452,12 @@ static int button_mask = 0; - (void)otherMouseDown:(NSEvent *)event { - if ((int) [event buttonNumber]!=2) + if ((int)[event buttonNumber] != 2) return; button_mask |= BUTTON_MASK_MIDDLE; InputEvent ev; - ev.type=InputEvent::MOUSE_BUTTON; + ev.type = InputEvent::MOUSE_BUTTON; ev.mouse_button.button_index = BUTTON_MIDDLE; ev.mouse_button.pressed = true; ev.mouse_button.x = mouse_x; @@ -472,7 +468,7 @@ static int button_mask = 0; ev.mouse_button.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->push_input(ev); -/* + /* _glfwInputMouseClick(window, (int) [event buttonNumber], GLFW_PRESS, @@ -486,12 +482,12 @@ static int button_mask = 0; - (void)otherMouseUp:(NSEvent *)event { - if ((int) [event buttonNumber]!=2) + if ((int)[event buttonNumber] != 2) return; button_mask &= ~BUTTON_MASK_MIDDLE; InputEvent ev; - ev.type=InputEvent::MOUSE_BUTTON; + ev.type = InputEvent::MOUSE_BUTTON; ev.mouse_button.button_index = BUTTON_MIDDLE; ev.mouse_button.pressed = false; ev.mouse_button.x = mouse_x; @@ -502,7 +498,7 @@ static int button_mask = 0; ev.mouse_button.mod = translateFlags([event modifierFlags]); OS_OSX::singleton->push_input(ev); -/* + /* _glfwInputMouseClick(window, (int) [event buttonNumber], GLFW_RELEASE, @@ -514,7 +510,7 @@ static int button_mask = 0; if (!OS_OSX::singleton) return; - if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode!=OS::MOUSE_MODE_CAPTURED) + 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) @@ -528,16 +524,15 @@ static int button_mask = 0; if (!OS_OSX::singleton) return; - if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode!=OS::MOUSE_MODE_CAPTURED) + 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); @@ -551,15 +546,17 @@ static int button_mask = 0; [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]; @@ -714,14 +711,14 @@ static int translateKey(unsigned int key) { ev.key.scancode = latin_keyboard_keycode_convert(translateKey([event keyCode])); ev.key.echo = [event isARepeat]; - NSString* characters = [event characters]; + 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]; + ev.key.unicode = [characters characterAtIndex:i]; OS_OSX::singleton->push_input(ev); - ev.key.scancode=0; + ev.key.scancode = 0; } } else { OS_OSX::singleton->push_input(ev); @@ -733,32 +730,32 @@ static int translateKey(unsigned int key) { int key = [event keyCode]; int mod = [event modifierFlags]; - ev.type=InputEvent::KEY; + ev.type = InputEvent::KEY; if (key == 0x36 || key == 0x37) { if (mod & NSCommandKeyMask) { - mod&= ~NSCommandKeyMask; + mod &= ~NSCommandKeyMask; ev.key.pressed = true; } else { ev.key.pressed = false; } } else if (key == 0x38 || key == 0x3c) { if (mod & NSShiftKeyMask) { - mod&= ~NSShiftKeyMask; + mod &= ~NSShiftKeyMask; ev.key.pressed = true; } else { ev.key.pressed = false; } } else if (key == 0x3a || key == 0x3d) { if (mod & NSAlternateKeyMask) { - mod&= ~NSAlternateKeyMask; + mod &= ~NSAlternateKeyMask; ev.key.pressed = true; } else { ev.key.pressed = false; } } else if (key == 0x3b || key == 0x3e) { if (mod & NSControlKeyMask) { - mod&= ~NSControlKeyMask; + mod &= ~NSControlKeyMask; ev.key.pressed = true; } else { ev.key.pressed = false; @@ -767,7 +764,7 @@ static int translateKey(unsigned int key) { return; } - ev.key.mod=translateFlags(mod); + ev.key.mod = translateFlags(mod); ev.key.scancode = latin_keyboard_keycode_convert(translateKey(key)); OS_OSX::singleton->push_input(ev); @@ -782,16 +779,16 @@ static int translateKey(unsigned int key) { 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); */ } -- (void)scrollWheel:(NSEvent *)event{ +- (void)scrollWheel:(NSEvent *)event { - double deltaX, deltaY; + double deltaX, deltaY; #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6) { @@ -814,8 +811,8 @@ static int translateKey(unsigned int key) { if (fabs(deltaY)) { InputEvent ev; - ev.type=InputEvent::MOUSE_BUTTON; - ev.mouse_button.button_index = deltaY >0 ? BUTTON_WHEEL_UP : BUTTON_WHEEL_DOWN; + 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; @@ -829,7 +826,7 @@ static int translateKey(unsigned int key) { if (fabs(deltaX)) { InputEvent ev; - ev.type=InputEvent::MOUSE_BUTTON; + 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; @@ -845,7 +842,8 @@ static int translateKey(unsigned int key) { @end -@interface GodotWindow : NSWindow {} +@interface GodotWindow : NSWindow { +} @end @implementation GodotWindow @@ -857,12 +855,11 @@ static int translateKey(unsigned int key) { @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"; } @@ -885,7 +882,6 @@ void OS_OSX::initialize_core() { DirAccess::make_default(DirAccess::ACCESS_FILESYSTEM); SemaphoreOSX::make_default(); - } static bool keyboard_layout_dirty = true; @@ -893,7 +889,7 @@ static void keyboardLayoutChanged(CFNotificationCenterRef center, void *observer keyboard_layout_dirty = true; } -void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) { +void OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) { /*** OSX INITIALIZATION ***/ /*** OSX INITIALIZATION ***/ @@ -903,33 +899,33 @@ 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; + 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); + 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 ); + ERR_FAIL_COND(window_object == nil); window_view = [[GodotContentView alloc] init]; @@ -937,14 +933,14 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi window_size.height = p_desired.height; #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 - if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6 && display_scale>1) { + if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6 && display_scale > 1) { [window_view setWantsBestResolutionOpenGLSurface:YES]; //if (current_videomode.resizable) [window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; } #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/ -// [window_object setTitle:[NSString stringWithUTF8String:"GodotEnginies"]]; + //[window_object setTitle:[NSString stringWithUTF8String:"GodotEnginies"]]; [window_object setContentView:window_view]; [window_object setDelegate:window_delegate]; [window_object setAcceptsMouseMovedEvents:YES]; @@ -960,9 +956,14 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi // OS X needs non-zero color size, so set resonable values 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); } +// 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); \ + } // Arbitrary array size here NSOpenGLPixelFormatAttribute attributes[40]; @@ -971,13 +972,13 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi ADD_ATTR(NSOpenGLPFAClosestPolicy); #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 - if (false/* use gl3*/) + if (false /* use gl3*/) ADD_ATTR2(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core); #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/ ADD_ATTR2(NSOpenGLPFAColorSize, colorBits); -/* + /* if (fbconfig->alphaBits > 0) ADD_ATTR2(NSOpenGLPFAAlphaSize, fbconfig->alphaBits); */ @@ -986,12 +987,12 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi ADD_ATTR2(NSOpenGLPFAStencilSize, 8); -/* + /* if (fbconfig->stereo) ADD_ATTR(NSOpenGLPFAStereo); */ -/* + /* if (fbconfig->samples > 0) { ADD_ATTR2(NSOpenGLPFASampleBuffers, 1); ADD_ATTR2(NSOpenGLPFASamples, fbconfig->samples); @@ -1007,11 +1008,11 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi #undef ADD_ATTR2 pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes]; - ERR_FAIL_COND( pixelFormat == nil); + ERR_FAIL_COND(pixelFormat == nil); context = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil]; - ERR_FAIL_COND(context==nil); + ERR_FAIL_COND(context == nil); [context setView:window_view]; @@ -1028,16 +1029,16 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi /*** END OSX INITIALIZATION ***/ /*** END OSX INITIALIZATION ***/ - bool use_gl2=p_video_driver!=1; + bool use_gl2 = p_video_driver != 1; AudioDriverManagerSW::add_driver(&audio_driver_osx); rasterizer = instance_RasterizerGLES2(); - visual_server = memnew( VisualServerRaster(rasterizer) ); + 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)); + if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) { + visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD)); } visual_server->init(); @@ -1045,60 +1046,59 @@ void OS_OSX::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi AudioDriverManagerSW::get_driver(p_audio_driver)->set_singleton(); - if (AudioDriverManagerSW::get_driver(p_audio_driver)->init()!=OK) { + if (AudioDriverManagerSW::get_driver(p_audio_driver)->init() != OK) { ERR_PRINT("Initializing audio failed."); } - sample_manager = memnew( SampleManagerMallocSW ); - audio_server = memnew( AudioServerSW(sample_manager) ); + sample_manager = memnew(SampleManagerMallocSW); + audio_server = memnew(AudioServerSW(sample_manager)); - audio_server->set_mixer_params(AudioMixerSW::INTERPOLATION_LINEAR,false); + audio_server->set_mixer_params(AudioMixerSW::INTERPOLATION_LINEAR, false); audio_server->init(); - spatial_sound_server = memnew( SpatialSoundServerSW ); + spatial_sound_server = memnew(SpatialSoundServerSW); spatial_sound_server->init(); - spatial_sound_2d_server = memnew( SpatialSound2DServerSW ); + spatial_sound_2d_server = memnew(SpatialSound2DServerSW); spatial_sound_2d_server->init(); - physics_server = memnew( PhysicsServerSW ); + physics_server = memnew(PhysicsServerSW); physics_server->init(); //physics_2d_server = memnew( Physics2DServerSW ); physics_2d_server = Physics2DServerWrapMT::init_server(); physics_2d_server->init(); - input = memnew( InputDefault ); - joystick_osx = memnew( JoystickOSX ); + input = memnew(InputDefault); + joystick_osx = memnew(JoystickOSX); _ensure_data_dir(); NSArray *screenArray = [NSScreen screens]; printf("nscreen count %i\n", (int)[screenArray count]); - for (int i=0; i<[screenArray count]; i++) { + for (int i = 0; i < [screenArray count]; i++) { float displayScale = 1.0; - if (display_scale>1.0 && [[screenArray objectAtIndex: i] respondsToSelector:@selector(backingScaleFactor)]) { - displayScale = [[screenArray objectAtIndex: i] backingScaleFactor]; + if (display_scale > 1.0 && [[screenArray objectAtIndex:i] respondsToSelector:@selector(backingScaleFactor)]) { + displayScale = [[screenArray objectAtIndex:i] backingScaleFactor]; } - NSRect nsrect = [[screenArray objectAtIndex: i] visibleFrame]; + NSRect nsrect = [[screenArray objectAtIndex:i] visibleFrame]; Rect2 rect = Rect2(nsrect.origin.x, nsrect.origin.y, nsrect.size.width, nsrect.size.height); - rect.pos*=displayScale; - rect.size*=displayScale; + rect.pos *= displayScale; + rect.size *= displayScale; screens.push_back(rect); - NSDictionary *description = [[screenArray objectAtIndex: i] deviceDescription]; + 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; + int dpi = (displayPixelSize.width * 25.4f / displayPhysicalSize.width) * displayScale; screen_dpi.push_back(dpi); - }; restore_rect = Rect2(get_window_position(), get_window_size()); } @@ -1134,11 +1134,10 @@ void OS_OSX::finalize() { screens.clear(); } -void OS_OSX::set_main_loop( MainLoop * p_main_loop ) { +void OS_OSX::set_main_loop(MainLoop *p_main_loop) { main_loop = p_main_loop; input->set_main_loop(p_main_loop); - } void OS_OSX::delete_main_loop() { @@ -1147,16 +1146,15 @@ void OS_OSX::delete_main_loop() { return; memdelete(main_loop); - main_loop=NULL; + main_loop = NULL; } - String OS_OSX::get_name() { return "OSX"; } -void OS_OSX::alert(const String& p_alert, const String& p_title) { +void OS_OSX::alert(const String &p_alert, const String &p_title) { // Set OS X-compliant variables NSAlert *window = [[NSAlert alloc] init]; NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()]; @@ -1174,10 +1172,10 @@ void OS_OSX::alert(const String& p_alert, const String& p_title) { void OS_OSX::set_cursor_shape(CursorShape p_shape) { - if (cursor_shape==p_shape) + if (cursor_shape == p_shape) return; - switch(p_shape) { + switch (p_shape) { case CURSOR_ARROW: [[NSCursor arrowCursor] set]; break; case CURSOR_IBEAM: [[NSCursor IBeamCursor] set]; break; case CURSOR_POINTING_HAND: [[NSCursor pointingHandCursor] set]; break; @@ -1198,15 +1196,13 @@ void OS_OSX::set_cursor_shape(CursorShape p_shape) { default: {}; } - cursor_shape=p_shape; + cursor_shape = 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 { @@ -1214,10 +1210,10 @@ bool OS_OSX::is_mouse_grab_enabled() const { return mouse_grab; } -void OS_OSX::warp_mouse_pos(const Point2& p_to) { +void OS_OSX::warp_mouse_pos(const Point2 &p_to) { //copied from windows impl with osx native calls - if (mouse_mode == MOUSE_MODE_CAPTURED){ + if (mouse_mode == MOUSE_MODE_CAPTURED) { mouse_x = p_to.x; mouse_y = p_to.y; } else { @@ -1234,7 +1230,7 @@ void OS_OSX::warp_mouse_pos(const Point2& p_to) { NSPoint pointOnScreen = [[window_view window] convertRectToScreen:pointInWindowRect].origin; //point in scren coords - CGPoint lMouseWarpPos = { pointOnScreen.x, pointOnScreen.y}; + CGPoint lMouseWarpPos = { pointOnScreen.x, pointOnScreen.y }; //do the warping CGEventSourceRef lEventRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState); @@ -1247,56 +1243,54 @@ void OS_OSX::warp_mouse_pos(const Point2& p_to) { Point2 OS_OSX::get_mouse_pos() const { - return Vector2(mouse_x,mouse_y); + 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) { +void OS_OSX::set_window_title(const String &p_title) { [window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]]; - } -void OS_OSX::set_icon(const Image& p_icon) { +void OS_OSX::set_icon(const Image &p_icon) { - Image img=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]; - ERR_FAIL_COND(imgrep==nil); + 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]; + ERR_FAIL_COND(imgrep == nil); uint8_t *pixels = [imgrep bitmapData]; - int len = img.get_width()*img.get_height(); + int len = img.get_width() * img.get_height(); DVector data = img.get_data(); DVector::Read r = data.read(); /* Premultiply the alpha channel */ - for (int i = 0; i *p_list,int p_screen) const { - +void OS_OSX::get_fullscreen_mode_list(List *p_list, int p_screen) const { } int OS_OSX::get_screen_count() const { @@ -1427,35 +1416,33 @@ Size2 OS_OSX::get_screen_size(int p_screen) const { Point2 OS_OSX::get_window_position() const { Size2 wp([window_object frame].origin.x, [window_object frame].origin.y); - wp*=display_scale; + wp *= display_scale; return wp; }; +void OS_OSX::set_window_position(const Point2 &p_position) { -void OS_OSX::set_window_position(const Point2& p_position) { - - Point2 size=p_position; - size/=display_scale; + Point2 size = p_position; + size /= display_scale; [window_object setFrame:NSMakeRect(size.x, size.y, [window_object frame].size.width, [window_object frame].size.height) display:YES]; }; Size2 OS_OSX::get_window_size() const { return window_size; - }; void OS_OSX::set_window_size(const Size2 p_size) { - Size2 size=p_size; + Size2 size = p_size; // NSRect used by setFrame includes the title bar, so add it to our size.y CGFloat menuBarHeight = [[[NSApplication sharedApplication] mainMenu] menuBarHeight]; if (menuBarHeight != 0.f) { - size.y+= menuBarHeight; + size.y += menuBarHeight; #if MAC_OS_X_VERSION_MAX_ALLOWED <= 101104 } else { - size.y+= [[NSStatusBar systemStatusBar] thickness]; + size.y += [[NSStatusBar systemStatusBar] thickness]; #endif } @@ -1478,7 +1465,7 @@ void OS_OSX::set_window_fullscreen(bool p_enabled) { bool OS_OSX::is_window_fullscreen() const { #if MAC_OS_X_VERSION_MAX_ALLOWED < 1070 - if ( [window_object respondsToSelector:@selector(isZoomed)] ) + if ([window_object respondsToSelector:@selector(isZoomed)]) return [window_object isZoomed]; #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/ @@ -1488,9 +1475,9 @@ bool OS_OSX::is_window_fullscreen() const { void OS_OSX::set_window_resizable(bool p_enabled) { if (p_enabled) - [window_object setStyleMask:[window_object styleMask] | NSResizableWindowMask ]; + [window_object setStyleMask:[window_object styleMask] | NSResizableWindowMask]; else - [window_object setStyleMask:[window_object styleMask] & ~NSResizableWindowMask ]; + [window_object setStyleMask:[window_object styleMask] & ~NSResizableWindowMask]; }; bool OS_OSX::is_window_resizable() const { @@ -1508,13 +1495,12 @@ void OS_OSX::set_window_minimized(bool p_enabled) { bool OS_OSX::is_window_minimized() const { - if ( [window_object respondsToSelector:@selector(isMiniaturized)]) + if ([window_object respondsToSelector:@selector(isMiniaturized)]) return [window_object isMiniaturized]; return minimized; }; - void OS_OSX::set_window_maximized(bool p_enabled) { if (p_enabled) { @@ -1533,7 +1519,6 @@ bool OS_OSX::is_window_maximized() const { return maximized; }; - void OS_OSX::move_window_to_foreground() { [window_object orderFrontRegardless]; @@ -1551,8 +1536,8 @@ String OS_OSX::get_executable_path() const { char pathbuf[PROC_PIDPATHINFO_MAXSIZE]; pid = getpid(); - ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf)); - if ( ret <= 0 ) { + ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf)); + if (ret <= 0) { return OS::get_executable_path(); } else { String path; @@ -1560,7 +1545,6 @@ String OS_OSX::get_executable_path() const { return path; } - } // Returns string representation of keys, if they are printable. @@ -1580,22 +1564,22 @@ static NSString *createStringForKeys(const CGKeyCode *keyCode, int length) { OSStatus err; CFMutableStringRef output = CFStringCreateMutable(NULL, 0); - for (int i=0; iparse_input_event(ev); } @@ -1681,16 +1666,16 @@ void OS_OSX::run() { set_window_fullscreen(true); } -// uint64_t last_ticks=get_ticks_usec(); + //uint64_t last_ticks=get_ticks_usec(); -// int frames=0; -// uint64_t frame=0; + //int frames=0; + //uint64_t frame=0; while (!force_quit) { process_events(); // get rid of pending events last_id = joystick_osx->process_joysticks(last_id); - if (Main::iteration()==true) + if (Main::iteration() == true) break; }; @@ -1716,7 +1701,7 @@ void OS_OSX::set_mouse_mode(MouseMode p_mode) { CGAssociateMouseAndMouseCursorPosition(true); } - mouse_mode=p_mode; + mouse_mode = p_mode; } OS::MouseMode OS_OSX::get_mouse_mode() const { @@ -1728,10 +1713,10 @@ String OS_OSX::get_joy_guid(int p_device) const { return input->get_joy_guid_remapped(p_device); } -OS_OSX* OS_OSX::singleton=NULL; +OS_OSX *OS_OSX::singleton = NULL; OS_OSX::OS_OSX() { - + mouse_mode = OS::MOUSE_MODE_VISIBLE; main_loop = NULL; singleton = this; @@ -1742,7 +1727,7 @@ 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"); @@ -1779,7 +1764,7 @@ OS_OSX::OS_OSX() { maximized = false; minimized = false; - window_size = Vector2(1024,600); + window_size = Vector2(1024, 600); zoomed = false; display_scale = 1.0; }