Files
UnrealEngineUWP/Engine/Source/Programs/IOS/MobileDeviceInterface/MobileDeviceInstance.cs
Jack Porter ae727f8dab Copying //UE4/Dev-Mobile to //UE4/Dev-Main (Source: //UE4/Dev-Mobile @ 3383462)
#lockdown Nick.Penwarden

==========================
MAJOR FEATURES + CHANGES
==========================

Change 3292174 on 2017/02/08 by Nick.Shin

	HTML5 emscripten: wasm and webgl2 support

	- Linux toolchain

	#jira UEPLAT-1437  Switch [to] web assembly

Change 3292193 on 2017/02/08 by Nick.Shin

	HTML5 emscripten: wasm and webgl2 support

	- ThirdParty libs compiled with new toolchain with wasm support

	#jira UEPLAT-1437  Switch [to] web assembly

Change 3292215 on 2017/02/08 by Nick.Shin

	HTML5 emscripten: wasm and wbegl2 support

	- emscripten toolchain

	#jira UEPLAT-1437  Switch [to] web assembly

Change 3292222 on 2017/02/08 by Nick.Shin

	HTML5 emscripten: wasm support

	- ENGINE changes (c# & cpp files)

	#jira UEPLAT-1437  Switch [to] web assembly

Change 3292223 on 2017/02/08 by Nick.Shin

	HTML5 merge ThirdParty lib build scripts from Dev-Platform to Dev-Mobile

Change 3292228 on 2017/02/08 by Nick.Shin

	HTML5 emscripten: webgl support

	- webgl patches
	- and a lot of UE4 patches to package HTML5 on LINUX
	- mostly from mozilla's jukka -- thx jukka!

	#jira  UEPLAT-828  (4.16)  Support ES3 / WebGL2 in HTML5

Change 3292285 on 2017/02/08 by Nick.Shin

	HTML5 emscripten: wasm and webgl2 support

	- Windows toolchain

	#jira UEPLAT-1437  Switch [to] web assembly

Change 3293994 on 2017/02/09 by Nick.Shin

	HTML5 emscripten: wasm and webgl2 support

	- OSX toolchain

	#jira UEPLAT-1437  Switch [to] web assembly

Change 3294391 on 2017/02/09 by Nick.Shin

	HTML5 "black box issues" revisited

	- jukka rewrote the window resize handler -- much cleaner and more straightforward

	#jira UE-36341  HTML5 - View is incorrectly drawn
	#jira UE-32311  Templates on Firefox/Chrome on HTML5 are not full screen during Launch On

Change 3296421 on 2017/02/10 by Jack.Porter

	Fix landscape spline segment splitting placing when using streaming levels

Change 3296587 on 2017/02/10 by Jack.Porter

	Additional fix for landscape spline segment splitting when using streaming levels

Change 3301241 on 2017/02/14 by Mi.Wang

	Fixed DeviceProfileEditor bug for incorrect clamp the Texture Mip LOD size. #jira UE-36237 #rb jack.porter

Change 3301387 on 2017/02/14 by Nick.Shin

	HTML5 emscripten: webgl support

	- webgl patches from mozilla's jukka
	  + hardware instancing
	  + glBlitFramebuffer
	  + GL AlaphaBlendOperation

	#jira  UEPLAT-828  (4.16)  Support ES3 / WebGL2 in HTML5

Change 3301405 on 2017/02/14 by Nick.Shin

	HTML5 plugin fix when blueprint projects are promoted to code projects automatically.

	#jira UE-41710  HTML5 - Package Failure - Failed to Produce item ProjectName-OnlineSubsystemNull.bc

Change 3302278 on 2017/02/14 by Omar.Rodriguez

	UE-36651: Mac Vulkan Android Projects crash on launch.

	* Glslang library has been built for Mac but flag was not updated
	* Set GlslangAvailable to true for Mac when building an Android project with vulkan

	#jira UE-36651

Change 3302773 on 2017/02/14 by Chris.Babcock

	Add a dropdown with some common console commands on Android (contributed by rafortis)
	#jira UE-40834
	#PR #3143
	#ue4
	#android

Change 3305604 on 2017/02/16 by Nick.Shin

	HTML5 webgl2 shader- turn on: instance static mesh vertex factory

	#jira  UEPLAT-828  (4.16)  Support ES3 / WebGL2 in HTML5

Change 3308154 on 2017/02/16 by Nick.Shin

	HTML5 GitHub PR

	#jira UE-42019  GitHub 3258 : Added suport for emscripten --pre-js and --post-js option when building for HTML5

Change 3308510 on 2017/02/16 by Nick.Shin

	HTML5 webgl2 shader fixes

	#jria UEMOB-201  Support ES3 / WebGL2 in HTML5

Change 3308971 on 2017/02/17 by Jack.Porter

	Fix for landscape painting when height<0 in the Ortho viewports

Change 3309075 on 2017/02/17 by Allan.Bentham

	Include static subject meshes when masking out modulated shadow casters.

	#jira UE-41581

Change 3309531 on 2017/02/17 by Chris.Babcock

	Handle large OBB files in APK
	#jira UE-41443
	#ue4
	#android

Change 3311320 on 2017/02/19 by Dmitriy.Dyomin

	Fixed: Particle Cutout Crashes On Mobile Devices That Don't Support Hardware Instancing (Mali-400 GPU)
	#jira UE-41970

Change 3311347 on 2017/02/20 by Dmitriy.Dyomin

	Fixed: Engine Crashes When Previewing ES3_1 With Material Using World Position Offset (Need Custom Stencil)
	#jira UE-41976

Change 3311398 on 2017/02/20 by Dmitriy.Dyomin

	Fixed: Landscapes do not render on PowerVR device
	#jira UE-35530

Change 3311428 on 2017/02/20 by Dmitriy.Dyomin

	Fixed: Exposure Is More Extreme In High-End Mobile Preview Modes
	#jira UE-42036

Change 3311448 on 2017/02/20 by Dmitriy.Dyomin

	Fixed: Packaged game Crashes on android after entering "Help" command twice
	#jira UE-41956

Change 3311587 on 2017/02/20 by Allan.Bentham

	ES2 GLSL - Silently swap all uint to ints
	#jira UE-41548

Change 3313930 on 2017/02/21 by Allan.Bentham

	Print literal uints as ints when generating ES2 code.
	#jira UE-41548

Change 3317924 on 2017/02/22 by Nick.Shin

	HTML5 emscripten: wasm & webgl2 support - RC1

	- Linux toolchain

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

Change 3317929 on 2017/02/22 by Nick.Shin

	HTML5 emscripten: wasm & webgl2 support - RC1

	- ThirdParty libs compiled with new toolchain with wasm and webgl2 support

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

Change 3317951 on 2017/02/22 by Nick.Shin

	HTML5 emscripten: wasm & webgl2 support - RC1

	- emscripten toolchain

	WARNING: emscripten/incoming/source/include/libc/bit (the file) might need to be deleted first

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

Change 3318004 on 2017/02/22 by Nick.Shin

	HTML5 emscripten: wasm & webgl2 support - RC1

	- windows toolchain

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

Change 3318669 on 2017/02/23 by Nick.Shin

	HTML5 emscripten: wasm & webgl2 support - RC1

	- OSX toolchain

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

Change 3318672 on 2017/02/23 by Nick.Shin

	HTML5 webgl2 shader fixes

	#jria UEMOB-201  Support ES3 / WebGL2 in HTML5

Change 3318819 on 2017/02/23 by Dmitriy.Dyomin

	Fixed: Rendering artifacts with bloom on iPhone7 Metal
	#jira UE-40978

Change 3319702 on 2017/02/23 by Chris.Babcock

	Disable eglSwapInterval since it can cause issues with some drivers
	#ue4
	#android

Change 3320880 on 2017/02/24 by Dmitriy.Dyomin

	Added r.Mobile.TonemapperFilm cvar which can be used to enable/disable filmic tonemapper on mobile, independently from desktop (disabled by default)
	#jira UEMOB-195

Change 3321042 on 2017/02/24 by Jack.Porter

	Fixed incorrect sizeof in Vulkan pipleine cache
	pointed out here: http://coconutlizard.co.uk/blog/ue4/ue4-its-a-size-jim/

	#code_review: rolando.caloca

Change 3322383 on 2017/02/24 by Chris.Babcock

	Fix issue with ad banner on Android 7.0 devices
	#jira UE-42390
	#ue4
	#android

Change 3322479 on 2017/02/24 by Omar.Rodriguez

	UEMOB-199 - WEX: Improved virtual keyboard for Android

	* Calculating the area covered by the virtual keyboard
	* Calling OnVirtualKeyboardShown and OnVirtualKeyboardHidden events
	* Passing the Rect of the area covered by the virtual keyboard OnVirtualKeyboardShown event

	#jira UEMOB-199

Change 3323353 on 2017/02/27 by Allan.Bentham

	Fix broken mobile scene captures when !mobileHDR and RHINeedsToSwitchVerticalAxis
	#jira UE-42191

Change 3323431 on 2017/02/27 by Allan.Bentham

	CIS fix

Change 3323687 on 2017/02/27 by Allan.Bentham

	Disable GRHINeedsUnatlasedCSMDepthsWorkaround for mobile devices.
	#jira UE-42131

Change 3324652 on 2017/02/28 by Dmitriy.Dyomin

	Fixed: Canvas elements appear darker on iOS Metal

Change 3324885 on 2017/02/28 by Jack.Porter

	Fixed "Minimum iOS Version" setting display name

	#jira UE-42270

Change 3324899 on 2017/02/28 by Jack.Porter

	GitHub 3063 : removed duplicate gc.MaxObjectsInGame setting in IOSEngine.ini
	#jira UE-40018

	#3063

Change 3324932 on 2017/02/28 by Jack.Porter

	GitHub 3257 : iPhonePackager errors in output log when opening project settings on Windows

	#jira UE-41984
	#3257
	#codereview: Peter.Sauerbrei

Change 3324956 on 2017/02/28 by Jack.Porter

	FOpenGLFrontend::GetMaxSamplers incorrect for IOS
	#jira UE-42038
	#3264

Change 3325478 on 2017/02/28 by Allan.Bentham

	PR # 3188   : Fix far distance bug with cascaded shadows on mobile (Metal) and PC mobile preview  (Contributed by ufna)

	#jira UE-41442

Change 3327300 on 2017/03/01 by Allan.Bentham

	PR #3175   : Fixes high quality reflection blending seams  (Contributed by kallehamalainen)
	#jira UE-41257

Change 3328917 on 2017/03/02 by Nick.Shin

	HTML5 project settings

	expose ini settings to edtior HTML5 project settings panel

	#jira UE-42331  Project Settings - HTML5 SDK - HTML Device population should be moved to an .ini
	#jira UE-41584  Editor locks up when adding an element for HTML5 devices on Mac
	#jira UE-41701  Editor freezes when setting browser filepath for inserted element in project settings

Change 3329169 on 2017/03/02 by Allan.Bentham

	increase render thread timeout to 1 minute for suntemple / android.
	Prevents low end devices timing out during load.
	#jira UE-40696

Change 3330849 on 2017/03/02 by Nick.Shin

	HTML5 project settings

	expose ini settings to edtior HTML5 project settings panel

	#jira UE-42331  Project Settings - HTML5 SDK - HTML Device population should be moved to an .ini

Change 3331078 on 2017/03/03 by Dmitriy.Dyomin

	Fixed: Device output log partial lines

	integrated from WEX (3250488)

Change 3331112 on 2017/03/03 by Dmitriy.Dyomin

	Reduced state setup for slate draw calls (saves about 4ms RT time on mobile)

	integrated from WEX (3256584)

Change 3331117 on 2017/03/03 by Dmitriy.Dyomin

	Fixed redundant blend state changes in opengl

	integrated from WEX (3256586)

Change 3331173 on 2017/03/03 by Dmitriy.Dyomin

	Slate pixel shaders will use half precision where possible on mobile

	integrated from WEX (3256656)

Change 3332865 on 2017/03/06 by Dmitriy.Dyomin

	Better MobileContentScaleFactor defaults for iOS devices
	#jira UEMOB-330

Change 3333129 on 2017/03/06 by Peter.Sauerbrei

	move to Library/Caches instead of documents for saved files
	re-enable iterative deploy on TVOS
	#jira UEMOB-284

Change 3334692 on 2017/03/06 by Jack.Porter

	Allow r.MobileContentScaleFactor to be changed at runtime on Android

	#jira UEMOB-173

Change 3336255 on 2017/03/07 by Nick.Shin

	HTML5 project settings

	marking SIMD and multithreading as experimental - these do not play nice with WASM builds currently...

	#jira UE-42331  Project Settings - HTML5 SDK - HTML Device population should be moved to an .ini

Change 3337094 on 2017/03/08 by Nick.Shin

	HTML5 project settings

	marking SIMD and multithreading as experimental - these do not play nice with WASM builds currently...

	#jira UE-42331  Project Settings - HTML5 SDK - HTML Device population should be moved to an .ini

Change 3338800 on 2017/03/08 by Chris.Babcock

	Update AAR handling to deal with versioning, subproject dependencies for resources, and scope
	#jira UE-42677
	#ue4
	#android

Change 3338813 on 2017/03/08 by Chris.Babcock

	Pass build configuration to UPL for access during packaging as $S(Configuration)
	#jira UE-42678
	#ue4
	#android
	#ios

Change 3339401 on 2017/03/09 by Alicia.Cano

	Android runtime permissions
	- Fix for WRITE_EXTERNAL_STORAGE if it is not granted at time of onCreate for non-shipping builds
	- Fix for Location Services
	- Fix for if target sdk is not set to 23+
	#jira UE-38512
	#android
	#rb: chris.babcock

Change 3340736 on 2017/03/09 by Chris.Babcock

	Implement support for new controllers (Xbox Wireless, SteelSeries Stratus XL, PS4) (contributed by TRS-justing)
	#jira UE-41965
	#PR #3254
	#ue4
	#android

Change 3340744 on 2017/03/09 by Jack.Porter

	Expose Custom Depth to Foliage
	#jira UE-6061

Change 3340849 on 2017/03/09 by Dmitriy.Dyomin

	Fixed: iOS movie become laggy and crashes when played in iPhone 6/6s.
	#jira UE-42351

Change 3341268 on 2017/03/10 by Alicia.Cano

	PR #2894: Initial VoiceModuleAndroid support. (Contributed by devbm)
	#jira UE-37945
	#android
	#rb: chris.babcock, jack.porter

Change 3341303 on 2017/03/10 by Allan.Bentham

	Remove optimisation that prevents full specular occulsion on mobile.
	PR #3186  : Specular can't be blocked on high-end mobile.
	#jira UE-41393

Change 3342304 on 2017/03/10 by Alicia.Cano

	build fix
	#rb: chris.babcock

Change 3343344 on 2017/03/13 by Alicia.Cano

	build fix
	#rb: chris.babcock

Change 3343591 on 2017/03/13 by Brent.Pease

	iOS multiplayer fix part 1. Correct byte ordering.

	#jira UE-34875

Change 3343669 on 2017/03/13 by Chris.Babcock

	Update carefullyredist script version
	#jira UE-42832

Change 3344212 on 2017/03/13 by Will.Fissler

	Various compile fixes for Xcode 8.3.
	These fixes must also be added to //UE4/Release-4.15.
	#jira UE-41313

Change 3344396 on 2017/03/13 by Chris.Babcock

	Fix Java 1.5 obsolete warnings
	#jira UE-42851
	#ue4
	#android

Change 3345132 on 2017/03/14 by Will.Fissler

	Added ifdef wrapper to check clang version for presentDrawable.

Change 3345336 on 2017/03/14 by Will.Fissler

	Moved #if (__clang_major__ > 8) || (__clang_major__ == 8 && __clang_minor__ >= 1) check inside of the presentDrawable method.

Change 3345460 on 2017/03/14 by Will.Fissler

	ifdef changes for presentDrawable. The last submission duped the changes, instead of merging. #rb none

Change 3346046 on 2017/03/14 by Will.Fissler

	Fixed MetalCommandBuffer.cpp [again] after last submission duped changes instead of merging.

Change 3346367 on 2017/03/14 by Chris.Babcock

	Fix issue with GoogleVR ARMv7 libraries included for other architectures in link
	#ue4
	#android

Change 3347682 on 2017/03/15 by Allan.Bentham

	Enable HW sRGB correction with retainer widget's render target.
	Use slate's gamma correction for mobile (where no such support exists)
	Render retainer box RT content with gamma correction.
	#jira UE-40967

Change 3348712 on 2017/03/15 by Nick.Shin

	HTML5 - upload to S3

	updated to AWS "signature version 4" authentication

	#jira UE-42525  HTML5 Upload to Amazon S3 fails with Incorrect Configuration error

Change 3349254 on 2017/03/16 by Jack.Porter

	Fix for crash using the mobile previewer when the LQ lightmap shader permutation is disabled.
	#jira UE-42971

Change 3349739 on 2017/03/16 by Nick.Shin

	HTML5 - upload to S3

	better error message feedback on upload failures

	#jira UE-42525  HTML5 Upload to Amazon S3 fails with Incorrect Configuration error

Change 3349765 on 2017/03/16 by Alicia.Cano

	Disable mouseover events in Mobile Previewer

	#jira UE-19903
	#mobile
	#rb: Jack.Porter

Change 3350049 on 2017/03/16 by Nick.Shin

	HTML5 - upload to S3

	folder in bucket is optional

	#jira UE-42525  HTML5 Upload to Amazon S3 fails with Incorrect Configuration error

Change 3350153 on 2017/03/16 by Nick.Shin

	HTML5 - upload to S3

	updated S3 public link generator

	#jira UE-42525  HTML5 Upload to Amazon S3 fails with Incorrect Configuration error

Change 3351582 on 2017/03/17 by Will.Fissler

	Reverting the attempted fix for Xcode 8.3: Result += " -mcpu=cortex-a9";

	Currently we cannot build arm64 for iOS with this change.

Change 3352085 on 2017/03/17 by Alicia.Cano

	iOS doesn't honor request to close the virtual keyboard leading to a crash
	#jira UE-36447
	#ios
	#rb:Peter.Sauerbrei

Change 3353313 on 2017/03/19 by Ben.Marsh

	Always allow large *.js files in Github.

Change 3354444 on 2017/03/20 by Nick.Shin

	HTML5 - upload to S3

	to help make it obvious that "upload to S3" checkbox is set/or not -- disable S3 details if checkbox for "uploading to S3" is not set

	#jira UE-42525  HTML5 Upload to Amazon S3 fails with Incorrect Configuration error

Change 3355618 on 2017/03/20 by Nick.Shin

	HTML5 Save Game System

	- ripped out HTML5 code [from Engine's SaveGameSystem.h] and placed it in HTML5Platform.cpp
	- cleaned up HTML5PlatformFile.cpp (make it match as clost to linux's version)
	- created HTML5's own PlatformFeature & SaveGameSystem files -- and updated HTML5PlatformMisc to make use of the the new HTML5 SaveGame code

	#jira UE-42081 Remove heinous HTML5 code from engine

Change 3355621 on 2017/03/20 by Nick.Shin

	remove temp debugging code

	#jira UE-42081 Remove heinous HTML5 code from engine

Change 3356937 on 2017/03/21 by Chris.Babcock

	Add "stat vulkanrhi" to new console dropdown
	#jira UE-43149
	#ue4
	#android

Change 3357652 on 2017/03/21 by Nick.Shin

	HTML5 performance speed ups

	added "use fixed timestep" setting option for HTML5 builds (this has been separated from Engine - General Settings - Framerate)
	- this is slightly different to smooth framerate and fixed framerate - thus, the timestep option was put in the HTML5 specific panel

	this option is based on the suggestions by jukka's post:
	- https://answers.unrealengine.com/questions/409629/smooth-frame-rate-and-use-fixed-frame-rate-should.html

	however, using this option will make the player "run faster" on (for example) thirdperson blueprint template -- but, it has no effect on other (for example) zen garden...

	#jira UE-30214 - Implement a warning message for fps settings

Change 3360415 on 2017/03/23 by Allan.Bentham

	Fix crash that occurs when ES3.1 preview is used with r.MobileHDR32bppMode modes.

Change 3360418 on 2017/03/23 by Allan.Bentham

	Disable filmic tonemapper if r.MobileHDR32bppMode is in use.
	#jira UE-40913

Change 3360557 on 2017/03/23 by Allan.Bentham

	Better fix for mobile CSM shadow flickering (UE-42131), now works for PC OpenGL based mobile preview.
	#jira UE-42131

Change 3362258 on 2017/03/23 by Dmitriy.Dyomin

	Fixed: Canvas texture element gamma issues on iOS Metal

Change 3362321 on 2017/03/24 by Dmitriy.Dyomin

	GitHub 3173 : MaterialAO support for mobile rendering path (contributed by kallehamalainen)

	#3173

Change 3363550 on 2017/03/24 by Alicia.Cano

	build fix for devices < Android 5.0
	#jira UE-43299
	#android
	#rb: chris.babcock

Change 3363687 on 2017/03/24 by Chris.Babcock

	Fix Android password hiding in input dialog
	#jira WEX-5159
	#ue4
	#android

Change 3365280 on 2017/03/27 by Dmitriy.Dyomin

	Fix for GL_EXT_shader_framebuffer_fetch on Zenfone5. Use UE_EXT_shader_framebuffer_fetch define on all devices to enable extension

Change 3365291 on 2017/03/27 by Dmitriy.Dyomin

	Copied form WEX CL# 3308653
	Fixed: Enabling shader cache causes crash on NVIDIA Shield

	#jira UE-41639

Change 3365293 on 2017/03/27 by Dmitriy.Dyomin

	GitHub 3411 : Fix crash in patching utils mount method (contributed by nverenik)
	#jira UE-43247
	#3411

Change 3365340 on 2017/03/27 by Dmitriy.Dyomin

	Fixed: Moving sublevel in world composition browser does not appear in Undo History
	#jira UE-35535

Change 3365564 on 2017/03/27 by Allan.Bentham

	SkyLightComponent now serializes IrradianceMap SH values.
	clicking Recapture sky button in mobile preview switches back to SM4/5 to update captures.
	Skylights that are dirty from load will trigger reflection capture update once shaders are rebuilt.
	#jira UE-42436

Change 3366282 on 2017/03/27 by Nick.Shin

	remove dead links

	these files to not exist anywhere in the make-3.81 subfolders

	#UDN-354501
	#jira none

Change 3366306 on 2017/03/27 by Nick.Shin

	HTML5 - disable multi-threading for wasm

	#jira UE-43219 - HTML5 disable multi-threading for wasm

Change 3366307 on 2017/03/27 by Nick.Shin

	HTML5 packaging Shipping builds

	big cleanup / additions to *gz file support for amazon s3

	* both, uploading to s3
	* and allowing s3 to host the games there

	#jira UE-43002 HTML5 in Shipping fails downloading symbols files
	#jria UE-43001 HTML5 Shipping Projects fail looking for compressed files when "Compress files during shipping packaging" is not selected.

Change 3367385 on 2017/03/28 by Allan.Bentham

	Display skylight serialization warning only when cooking for mobile platforms.
	#jira UE-42436

Change 3368583 on 2017/03/28 by Chris.Babcock

	Expose JAVA_HOME setting in Android SDK project settings on Mac
	#jira UE-43418
	#ue4
	#android

Change 3368803 on 2017/03/28 by Chris.Babcock

	Fix features requested in manifest for "Daydream and Cardboard" mode
	#jira UE-43314
	#ue4
	#android

Change 3369087 on 2017/03/28 by Jack.Porter

	Changed tooltip and added supported devices in paretheses for Android Mobile Deferred / ES31+AEP
	#jira UE-42438

Change 3369372 on 2017/03/29 by Allan.Bentham

	Fix disappearing meshes when r.mobile.allowdistancefieldshadows is disabled.
	#jira UE-43366

Change 3369381 on 2017/03/29 by Jack.Porter

	Show warnings when mobile shader permutations required for rendering are disbaled
	Made FReadOnlyCVARCache a singleton and added mobile CVars, used for MobileBasePassRendering.
	#jira UE-43050

Change 3369430 on 2017/03/29 by Allan.Bentham

	fix CIS build

Change 3369740 on 2017/03/29 by Allan.Bentham

	Added Android option to enable builds with hidden symbol visbility by default. (bBuildWithHiddenSymbolVisibility)
	Android links with -gc-sections to remove unused code/data
	Add JNI_METHOD for java accessible native functions, fixed up existing JNI functions to use macro.
	Add support for map file generation with android.
	Add 'bBuildWithHiddenSymbolVisibility' to AndroidPlatform.HasDefaultBuildConfig()
	bBuildWithHiddenSymbolVisibility defaults to false in BaseEngine.ini

	#jira UEMOB-168

Change 3369975 on 2017/03/29 by Nick.Shin

	HTML5 - AWS S3 shareable link for shipping builds corrected

	#jira UE-43379 Amazon S3 Shareable link does not generate correct filepath.

Change 3369998 on 2017/03/29 by Nick.Shin

	HTML5 python build scripts

	PR:
	1cb836d43c

	#jira none

Change 3370214 on 2017/03/29 by Nick.Shin

	HTML5 - default bUseFixedTimeStep to false...

	#jira UE-43380 - Default HTML5 gamespeed is faster than equivalent platforms

Change 3370762 on 2017/03/29 by Chris.Babcock

	Fixes to new keyboard for Android
	- Ensure the local scope ScreenRect passed into OnVirtualKeyboardShown in AndroidJNI is captured by value instead of by reference.
	- Moved ShowVirtualKeyboardInput's bKeyboardShowing early-out checks into the UI thread task. This allows the keyboard to continue showing when changing focus between multiple EditableTextBox widgets.
	#ue4
	#android

Change 3371344 on 2017/03/30 by Jack.Porter

	Fixed issue where Vulkan screenshot R/B channels were reversed on Android
	#jira UE-43479

Change 3372926 on 2017/03/30 by Peter.Sauerbrei

	start the process of sunsetting 32-bit and GLES2 on iOS
	#jira UE-42266

Change 3372970 on 2017/03/30 by Nick.Shin

	HTML5 - 1.37.9 emscripten: wasm & webgl2 support

	- windows toolchain

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

	#rn

Change 3372989 on 2017/03/30 by Peter.Sauerbrei

	fix for Xcode 8.3 build with 32-bit

Change 3373007 on 2017/03/30 by Peter.Sauerbrei

	fix for crash when online subsystem is disabled on IOS

Change 3373108 on 2017/03/30 by Nick.Shin

	HTML5 - 1.37.9 emscripten: wasm & webgl2 support

	- emscripten toolchain

	WARNING: emscripten/incoming/source/include/libc/bit (the file) might need to be deleted first

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

	#rn

Change 3373163 on 2017/03/30 by Nick.Shin

	HTML5 - 1.37.9 emscripten: wasm & webgl2 support

	- OSX toolchain

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

	#rn

Change 3373169 on 2017/03/30 by Nick.Shin

	HTML5 - 1.37.9 emscripten: wasm & webgl2 support

	license file updated

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

	#rnx

Change 3373287 on 2017/03/30 by Nick.Shin

	HTML5 - 1.36.11 emscripten - remove old SDK

	#jira none

	#rnx

Change 3373289 on 2017/03/30 by Nick.Shin

	HTML5 - 1.37.9 emscripten: wasm & webgl2 support

	- Linux toolchain

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

	#rn

Change 3373595 on 2017/03/30 by Chris.Babcock

	Reenable GooglePlay for ARM64 now that it doesn't crash
	#jira UE-36198
	#ue4
	#android

Change 3373606 on 2017/03/30 by Chris.Babcock

	Submitting Allan's shelved EXT_shader_framebuffer_fetch fix
	#ue4
	#android

Change 3375456 on 2017/03/31 by Chris.Babcock

	Add missing keycodes for Android keyboard (@ and #)
	#jira WEX-5777
	#ue4
	#android

Change 3376309 on 2017/04/03 by Allan.Bentham

	Fix overflow issues with mobile DoF.

Change 3377041 on 2017/04/03 by Will.Fissler

	Adding Testbed content for PlatformShowcase.

Change 3377582 on 2017/04/03 by Alicia.Cano

	adding back in GET_ACCOUNTS permission as it is required for Reset Achievements

	#jira: UE-43265
	#android
	#rb: Chris.Babcock

Change 3377643 on 2017/04/03 by Peter.Sauerbrei

	fix for memory leak in MallocBinned
	#jira UE-43008

Change 3378033 on 2017/04/04 by Nick.Shin

	HTML5 - 1.37.9 emscripten: wasm & webgl2 support

	- ThirdParty libs compiled with new toolchain with wasm and webgl2 support

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

	#rn

Change 3378034 on 2017/04/04 by Nick.Shin

	HTML5 - 1.37.9 emscripten: wasm & webgl2 support

	- ThirdParty build scripts

	#jira UEMOB-263  Switch [to] web assembly
	#jira UEMOB-201  Support ES3 / WebGL2 in HTML5

Change 3378035 on 2017/04/04 by Nick.Shin

	HTML5 - Update GameX template to make it work with trunk Emscripten

	PR
	dc2b26f452 (commitcomment-21454978)

	#jira none

	#rn

Change 3378044 on 2017/04/04 by Nick.Shin

	HTML5 harfbuzz - double checking recompiled with NO multithreading

	wasm currently does not support pthreads

	*** THIS IS STILL WIP ***
	checking in to match 3rd party libs compiled configuration

	#jira UE-28588 - Build HarfBuzz for HTML5

	#rnx

Change 3378264 on 2017/04/04 by Allan.Bentham

	Fix crash when using consolas font on android sdk 24
	#jira UE-43464

Change 3379097 on 2017/04/04 by Nick.Shin

	CIS HTML5 build warning fix

	#jria none

	#rnx

Change 3379333 on 2017/04/04 by Chris.Babcock

	Prevent inserting extra permissions into manifest multiple times
	#jira UE-43583
	#ue4
	#android

Change 3380870 on 2017/04/05 by Chris.Babcock

	Fix merge issue

Change 3380898 on 2017/04/05 by Chris.Babcock

	Fixed again

Change 3381443 on 2017/04/05 by Chris.Babcock

	Fix for GearVR non-unity build
	#ue4
	#android

Change 3381941 on 2017/04/05 by Chris.Babcock

	Fix HTTPChunkInstaller texture format checks and missing #define warning
	#jira UE-43706
	#ue4
	#android

Change 3382056 on 2017/04/05 by Chris.Babcock

	Updates to Android AARs needed for Facebook plugin

Change 3382097 on 2017/04/05 by Chris.Babcock

	Disable java console cmd receiver only in shipping builds
	#jira UE-43710
	#ue4
	#android

Change 3382497 on 2017/04/06 by Allan.Bentham

	Fix Fortnite Cooked Server crashes when joining game from lobby.
	#jira UE-43695

Change 3383227 on 2017/04/06 by Will.Fissler

	Reverted case sensitive change, from yesterday, and implemented a pragma instead.

	#jira UE-41313

[CL 3383473 by Jack Porter in Main branch]
2017-04-06 16:13:17 -04:00

1537 lines
53 KiB
C#

// Software License Agreement (BSD License)
//
// Copyright (c) 2007, Peter Dennis Bartok <PeterDennisBartok@gmail.com>
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the
// following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// * Neither the name of Peter Dennis Bartok nor the names of its
// contributors may be used to endorse or promote products
// derived from this software without specific prior
// written permission of Yahoo! Inc.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;
using MobileDeviceInterface;
namespace Manzana
{
public class MobileDeviceInstanceManager
{
/// <summary>
/// Registered device notification callback
/// </summary>
private static DeviceNotificationCallback DeviceCallbackHandle;
/// <summary>
/// The <c>Connect</c> event is triggered when a iPhone is connected to the computer
/// </summary>
public static event ConnectEventHandler ConnectEH;
/// <summary>
/// The <c>Disconnect</c> event is triggered when the iPhone is disconnected from the computer
/// </summary>
public static event ConnectEventHandler DisconnectEH;
/// <summary>
/// List of connected devices (device ptr -> device instance)
/// </summary>
public static Dictionary<TypedPtr<AppleMobileDeviceConnection>, MobileDeviceInstance> ConnectedDevices = new Dictionary<TypedPtr<AppleMobileDeviceConnection>, MobileDeviceInstance>();
public static IEnumerable<MobileDeviceInstance> GetSnapshotInstanceList()
{
// Clone a copy to prevent problems from delayed enumeration
List<MobileDeviceInstance> Result = new List<MobileDeviceInstance>();
Result.AddRange(ConnectedDevices.Values);
return Result;
}
/// <summary>
/// Returns true if any devices are currently connected
/// </summary>
/// <returns></returns>
public static bool AreAnyDevicesConnected()
{
lock (ConnectedDevices)
{
return ConnectedDevices.Count > 0;
}
}
/// <summary>
/// Initialize the mobile device manager, which handles discovery of connected Apple mobile devices
/// </summary>
/// <param name="myConnectHandler"></param>
/// <param name="myDisconnectHandler"></param>
public static void Initialize(ConnectEventHandler myConnectHandler, ConnectEventHandler myDisconnectHandler)
{
if (MobileDevice.DeviceImpl == null)
{
return;
}
ConnectEH += myConnectHandler;
DisconnectEH += myDisconnectHandler;
DeviceCallbackHandle = new DeviceNotificationCallback(NotifyCallback);
int ret = MobileDevice.DeviceImpl.NotificationSubscribe(DeviceCallbackHandle);
if (ret != 0)
{
throw new Exception("AMDeviceNotificationSubscribe failed with error " + ret);
}
}
/// <summary>
/// Raises the <see>Connect</see> event.
/// </summary>
/// <param name="args">A <see cref="ConnectEventArgs"/> that contains the event data.</param>
protected static void OnConnect(ConnectEventArgs args)
{
ConnectEventHandler handler = ConnectEH;
if (handler != null)
{
handler(null, args);
}
}
/// <summary>
/// Raises the <see>Disconnect</see> event.
/// </summary>
/// <param name="args">A <see cref="ConnectEventArgs"/> that contains the event data.</param>
protected static void OnDisconnect(ConnectEventArgs args)
{
ConnectEventHandler handler = DisconnectEH;
if (handler != null)
{
handler(null, args);
}
}
private static void NotifyCallback(ref AMDeviceNotificationCallbackInfo callback)
{
if (callback.msg == NotificationMessage.Connected)
{
MobileDeviceInstance Inst;
if (ConnectedDevices.TryGetValue(callback.dev, out Inst))
{
// Already connected, not sure why we got another message...
}
else
{
Inst = new MobileDeviceInstance(callback.dev);
ConnectedDevices.Add(callback.dev, Inst);
}
if (Inst.ConnectToPhone())
{
OnConnect(new ConnectEventArgs(callback));
}
}
else if (callback.msg == NotificationMessage.Disconnected)
{
MobileDeviceInstance Inst;
if (ConnectedDevices.TryGetValue(callback.dev, out Inst))
{
Inst.connected = false;
OnDisconnect(new ConnectEventArgs(callback));
ConnectedDevices.Remove(callback.dev);
}
}
}
}
/// <summary>
/// Exposes access to a mobile device running iOS
/// </summary>
public class MobileDeviceInstance
{
#region Locals
private DeviceRestoreNotificationCallback drn1;
private DeviceRestoreNotificationCallback drn2;
private DeviceRestoreNotificationCallback drn3;
private DeviceRestoreNotificationCallback drn4;
internal TypedPtr<AppleMobileDeviceConnection> iPhoneHandle;
internal TypedPtr<AFCCommConnection> AFCCommsHandle;
internal IntPtr hService;
internal IntPtr hSyslogService;
internal IntPtr hInstallService;
public bool connected;
private string current_directory;
#endregion // Locals
#region Constructors
/// <summary>
/// Initializes a new iPhone object.
/// </summary>
private void doConstruction()
{
drn1 = new DeviceRestoreNotificationCallback(DfuConnectCallback);
drn2 = new DeviceRestoreNotificationCallback(RecoveryConnectCallback);
drn3 = new DeviceRestoreNotificationCallback(DfuDisconnectCallback);
drn4 = new DeviceRestoreNotificationCallback(RecoveryDisconnectCallback);
int ret = MobileDevice.DeviceImpl.RestoreRegisterForDeviceNotifications(drn1, drn2, drn3, drn4, 0, IntPtr.Zero);
if (ret != 0)
{
throw new Exception("AMRestoreRegisterForDeviceNotifications failed with error " + ret);
}
current_directory = "/";
}
/// <summary>
/// Creates a new iPhone object. If an iPhone is connected to the computer, a connection will automatically be opened.
/// </summary>
public MobileDeviceInstance(TypedPtr<AppleMobileDeviceConnection> Connection)
{
iPhoneHandle = Connection;
doConstruction();
}
#endregion // Constructors
#region Properties
/// <summary>
/// Gets the current activation state of the phone
/// </summary>
public string ActivationState
{
get
{
return MobileDevice.AMDeviceCopyValue(iPhoneHandle, "ActivationState");
}
}
/// <summary>
/// Returns true if an iPhone is connected to the computer
/// </summary>
public bool IsConnected
{
get
{
return connected;
}
}
/// <summary>
/// Returns the Device information about the connected iPhone
/// </summary>
public TypedPtr<AppleMobileDeviceConnection> Device
{
get
{
return iPhoneHandle;
}
}
///<summary>
/// Returns the 40-character UUID of the device
///</summary>
public string DeviceId
{
get
{
return MobileDevice.AMDeviceCopyValue(iPhoneHandle, "UniqueDeviceID");
}
}
///<summary>
/// Returns the type of the device, should be either 'iPhone' or 'iPod'.
///</summary>
public string DeviceType
{
get
{
return MobileDevice.AMDeviceCopyValue(iPhoneHandle, "DeviceClass");
}
}
///<summary>
/// Returns the current OS version running on the device (2.0, 2.2, 3.0, 3.1, etc).
///</summary>
public string DeviceVersion
{
get
{
return MobileDevice.AMDeviceCopyValue(iPhoneHandle, "ProductVersion");
}
}
///<summary>
/// Returns the name of the device, like "Dan's iPhone"
///</summary>
public string DeviceName
{
get
{
return MobileDevice.AMDeviceCopyValue(iPhoneHandle, "DeviceName");
}
}
///<summary>
/// Returns the model number of the device, like "MA712"
///</summary>
public string ModelNumber
{
get
{
return MobileDevice.AMDeviceCopyValue(iPhoneHandle, "ModelNumber");
}
}
///<summary>
/// Returns the product type of the device, like "iPhone1,1"
///</summary>
public string ProductType
{
get
{
return MobileDevice.AMDeviceCopyValue(iPhoneHandle, "ProductType");
}
}
/// <summary>
/// Returns the handle to the iPhone com.apple.afc service
/// </summary>
public TypedPtr<AFCCommConnection> AFCHandle
{
get
{
return AFCCommsHandle;
}
}
/// <summary>
/// Gets/Sets the current working directory, used by all file and directory methods
/// </summary>
public string CurrentDirectory
{
get
{
return current_directory;
}
set
{
string new_path = FullPath(current_directory, value);
if (!IsDirectory(new_path))
{
throw new Exception("Invalid directory specified");
}
current_directory = new_path;
}
}
#endregion // Properties
#region Events
/// <summary>
/// Write Me
/// </summary>
public event EventHandler DfuConnect;
/// <summary>
/// Raises the <see>DfuConnect</see> event.
/// </summary>
/// <param name="args">A <see cref="DeviceNotificationEventArgs"/> that contains the event data.</param>
protected void OnDfuConnect(DeviceNotificationEventArgs args)
{
EventHandler handler = DfuConnect;
if (handler != null)
{
handler(this, args);
}
}
/// <summary>
/// Write Me
/// </summary>
public event EventHandler DfuDisconnect;
/// <summary>
/// Raises the <see>DfiDisconnect</see> event.
/// </summary>
/// <param name="args">A <see cref="DeviceNotificationEventArgs"/> that contains the event data.</param>
protected void OnDfuDisconnect(DeviceNotificationEventArgs args)
{
EventHandler handler = DfuDisconnect;
if (handler != null)
{
handler(this, args);
}
}
/// <summary>
/// The RecoveryModeEnter event is triggered when the attached iPhone enters Recovery Mode
/// </summary>
public event EventHandler RecoveryModeEnter;
/// <summary>
/// Raises the <see>RecoveryModeEnter</see> event.
/// </summary>
/// <param name="args">A <see cref="DeviceNotificationEventArgs"/> that contains the event data.</param>
protected void OnRecoveryModeEnter(DeviceNotificationEventArgs args)
{
EventHandler handler = RecoveryModeEnter;
if (handler != null)
{
handler(this, args);
}
}
/// <summary>
/// The RecoveryModeLeave event is triggered when the attached iPhone leaves Recovery Mode
/// </summary>
public event EventHandler RecoveryModeLeave;
/// <summary>
/// Raises the <see>RecoveryModeLeave</see> event.
/// </summary>
/// <param name="args">A <see cref="DeviceNotificationEventArgs"/> that contains the event data.</param>
protected void OnRecoveryModeLeave(DeviceNotificationEventArgs args)
{
EventHandler handler = RecoveryModeLeave;
if (handler != null)
{
handler(this, args);
}
}
#endregion // Events
#region Filesystem
/// <summary>
/// Sanitizes a filename for use on PC (just the filename, not a full path)
/// </summary>
static public string SanitizeFilename(string InputFilename)
{
char[] Filename = InputFilename.ToCharArray();
char[] BadChars = Path.GetInvalidFileNameChars();
for (int i = 0; i < Filename.Length; ++i)
{
foreach (char BadChar in BadChars)
{
if (Filename[i] == BadChar)
{
Filename[i] = '_';
break;
}
}
}
return new string(Filename);
}
/// <summary>
/// Sanitizes a path for use on PC (just the path, no filename)
/// </summary>
static public string SanitizePathNoFilename(string InputPath)
{
char[] DirectoryName = InputPath.ToCharArray();
char[] BadChars = Path.GetInvalidPathChars();
for (int i = 0; i < DirectoryName.Length; ++i)
{
foreach (char BadChar in BadChars)
{
if ((DirectoryName[i] == BadChar) || (DirectoryName[i] == ':'))
{
DirectoryName[i] = '_';
break;
}
}
}
return new string(DirectoryName);
}
void RecursiveBackup(string SourceFolderOnDevice, string TargetFolderOnPC)
{
string[] Directories = GetDirectories(SourceFolderOnDevice);
foreach (string Directory in Directories)
{
string NewSourceFolder = SourceFolderOnDevice + Directory + "/";
string NewTargetFolder = Path.Combine(TargetFolderOnPC, SanitizePathNoFilename(Directory));
RecursiveBackup(NewSourceFolder, NewTargetFolder);
}
string[] Filenames = GetFiles(SourceFolderOnDevice);
foreach (string Filename in Filenames)
{
string SourceFilename = SourceFolderOnDevice + Filename;
string DestFilename = Path.Combine(TargetFolderOnPC, SanitizeFilename(Filename));
WriteProgressLine("Copying '{0}' -> '{1}' ...", 0, SourceFilename, DestFilename);
CopyFileFromPhone(DestFilename, SourceFilename, 1024 * 1024);
}
}
void RecursiveCopy(string SourceFolderOnPC, string TargetFolderOnDevice)
{
string[] Directories = System.IO.Directory.GetDirectories(SourceFolderOnPC);
foreach (string Directory in Directories)
{
string NewSourceFolder = Directory;
string NewTargetFolder = TargetFolderOnDevice + Directory.Substring(Directory.LastIndexOf(Path.DirectorySeparatorChar)+1) + "/";
WriteProgressLine("Copying folder {0} to {1}", 0, NewSourceFolder, NewTargetFolder);
RecursiveCopy(NewSourceFolder, NewTargetFolder);
}
string[] Filenames = System.IO.Directory.GetFiles(SourceFolderOnPC);
foreach (string Filename in Filenames)
{
string SourceFilename = Filename;
string DestFilename = TargetFolderOnDevice + Path.GetFileName(Filename);
WriteProgressLine("Copying '{0}' -> '{1}' ...", 0, SourceFilename, DestFilename);
CopyFileToPhone(SourceFilename, DestFilename, 1024 * 1024);
}
}
public void DumpInstalledApplications()
{
Dictionary<string, object> AppBundles;
MobileDevice.DeviceImpl.LookupApplications(iPhoneHandle, IntPtr.Zero, out AppBundles);
foreach (var Bundle in AppBundles)
{
WriteProgressLine(String.Format("Application bundle {0} has the following pairs:", Bundle.Key), 0);
Dictionary<object, object> BundlePairs = (Dictionary<object, object>)Bundle.Value;
foreach (var KVP in BundlePairs)
{
WriteProgressLine(String.Format(" {0} -> {1}", KVP.Key, KVP.Value), 0);
}
}
}
/// <summary>
/// Tries to back up all of the files on a phone in a particular directory to the PC
/// (requires the bundle identifier to be able to mount that directory)
/// </summary>
public bool TryBackup(string BundleIdentifier, string SourceFolderOnDevice, string TargetFolderOnPC)
{
if (ConnectToBundle(BundleIdentifier))
{
WriteProgressLine("Connected to bundle '{0}'", 0, BundleIdentifier);
try
{
RecursiveBackup(SourceFolderOnDevice, TargetFolderOnPC);
return true;
}
catch (Exception ex)
{
WriteProgressLine("Failed to transfer a file, extended error is '{0}'", 100, ex.Message);
return false;
}
}
else
{
WriteProgressLine("Error: Failed to connect to bundle '{0}'", 100, BundleIdentifier);
return false;
}
}
/// <summary>
/// Tries to copy all of the files in a particular directory on the PC to the phone directory
/// (requires the bundle identifier to be able to mount that directory)
/// </summary>
public bool TryCopy(string BundleIdentifier, string SourceFolderOnPC, string TargetFolderOnDevice)
{
if (ConnectToBundle(BundleIdentifier))
{
WriteProgressLine("Connected to bundle '{0}'", 0, BundleIdentifier);
try
{
RecursiveCopy(SourceFolderOnPC, TargetFolderOnDevice);
return true;
}
catch (Exception ex)
{
WriteProgressLine("Failed to transfer a file, extended error is '{0}'", 100, ex.Message);
return false;
}
}
else
{
WriteProgressLine("Error: Failed to connect to bundle '{0}'", 100, BundleIdentifier);
return false;
}
}
/// <summary>
/// Tries to copy all of the files in the manifest on the PC to the library directory
/// (requires the bundle identifier to be able to mount that directory)
/// </summary>
public bool TryCopy(string BundleIdentifier, string Manifest)
{
if (ConnectToBundle(BundleIdentifier))
{
WriteProgressLine("Connected to bundle '{0}'", 0, BundleIdentifier);
try
{
string BaseFolder = Path.GetDirectoryName(Manifest);
string Files = File.ReadAllText(Manifest);
string[] FileList = Files.Split('\n');
foreach (string Filename in FileList)
{
if (!string.IsNullOrEmpty(Filename) && !string.IsNullOrWhiteSpace(Filename))
{
string Trimmed = Filename.Trim();
string SourceFilename = BaseFolder + "\\" + Trimmed;
SourceFilename = SourceFilename.Replace('/', '\\');
string DestFilename = "/Library/Caches/" + Trimmed.Replace("cookeddata/", "");
DestFilename = DestFilename.Replace('\\', '/');
SourceFilename = SourceFilename.Replace('\\', Path.DirectorySeparatorChar);
WriteProgressLine("Copying '{0}' -> '{1}' ...", 0, SourceFilename, DestFilename);
CopyFileToPhone(SourceFilename, DestFilename, 1024 * 1024);
}
}
return true;
}
catch (Exception ex)
{
WriteProgressLine("Failed to transfer a file, extended error is '{0}'", 100, ex.Message);
return false;
}
}
else
{
WriteProgressLine("Error: Failed to connect to bundle '{0}'", 100, BundleIdentifier);
return false;
}
}
/// <summary>
/// Tries to copy all of the files in a particular directory on the PC to the phone directory
/// (requires the bundle identifier to be able to mount that directory)
/// </summary>
public bool TryBackup(string BundleIdentifier, string[] Files)
{
if (ConnectToBundle(BundleIdentifier))
{
WriteProgressLine("Connected to bundle '{0}'", 0, BundleIdentifier);
try
{
string SafeDeviceName = MobileDeviceInstance.SanitizePathNoFilename(DeviceName);
foreach (string Filename in Files)
{
// string BaseFolder = Path.GetDirectoryName(Filename);
string Manifest = Path.GetDirectoryName(Filename) + "\\" + SafeDeviceName + "_" + Path.GetFileName(Filename);
CopyFileFromPhone(Manifest, "/Library/Caches/" + Path.GetFileName(Filename), 1024 * 1024);
}
return true;
}
catch (Exception ex)
{
WriteProgressLine("Failed to transfer a file, extended error is '{0}'", 100, ex.Message);
return false;
}
}
else
{
string SafeDeviceName = MobileDeviceInstance.SanitizePathNoFilename(DeviceName);
foreach (string Filename in Files)
{
// string BaseFolder = Path.GetDirectoryName(Filename);
string Manifest = Path.GetDirectoryName (Filename) + "\\" + SafeDeviceName + "_" + Path.GetFileName (Filename);
WriteProgressLine("File to be written '{0}'", 100, Manifest);
File.WriteAllText (Manifest, "");
}
WriteProgressLine("Error: Failed to connect to bundle '{0}'", 100, BundleIdentifier);
return false;
}
}
/// <summary>
/// Returns the names of files in a specified directory
/// </summary>
/// <param name="path">The directory from which to retrieve the files.</param>
/// <returns>A <c>String</c> array of file names in the specified directory. Names are relative to the provided directory</returns>
public string[] GetFiles(string path)
{
return GetFiles(path, false);
}
public string[] GetFiles(string path, bool bIncludeDirs)
{
if (!IsConnected)
{
throw new Exception("Not connected to phone");
}
string full_path = FullPath(CurrentDirectory, path);
IntPtr hAFCDir = IntPtr.Zero;
if (MobileDevice.DeviceImpl.DirectoryOpen(AFCCommsHandle, full_path, ref hAFCDir) != 0)
{
throw new Exception("Path does not exist");
}
string buffer = null;
ArrayList paths = new ArrayList();
MobileDevice.DeviceImpl.DirectoryRead(AFCCommsHandle, hAFCDir, ref buffer);
while (buffer != null)
{
if (!IsDirectory(FullPath(full_path, buffer)))
{
paths.Add(buffer);
}
else
{
if (bIncludeDirs)
{
paths.Add(buffer + "/");
}
}
MobileDevice.DeviceImpl.DirectoryRead(AFCCommsHandle, hAFCDir, ref buffer);
}
MobileDevice.DeviceImpl.DirectoryClose(AFCCommsHandle, hAFCDir);
return (string[])paths.ToArray(typeof(string));
}
/// <summary>
/// Returns the FileInfo dictionary
/// </summary>
/// <param name="path">The file or directory for which to retrieve information.</param>
public Dictionary<string, string> GetFileInfo(string path)
{
Dictionary<string, string> ans = new Dictionary<string, string>();
TypedPtr<AFCDictionary> Data;
int ret = MobileDevice.DeviceImpl.FileInfoOpen(AFCCommsHandle, path, out Data);
if ((ret == 0) && (Data.Handle != IntPtr.Zero))
{
IntPtr pname;
IntPtr pvalue;
while (MobileDevice.DeviceImpl.KeyValueRead(Data, out pname, out pvalue) == 0 && pname != IntPtr.Zero && pvalue != IntPtr.Zero)
{
string name = Marshal.PtrToStringAnsi(pname);
string value = Marshal.PtrToStringAnsi(pvalue);
if ((name != null) && (value != null))
{
ans.Add(name, value);
}
else
{
break;
}
}
MobileDevice.DeviceImpl.KeyValueClose(Data);
}
return ans;
}
/// <summary>
/// Returns the st_ifmt of a path
/// </summary>
/// <param name="path">Path to query</param>
/// <returns>string representing value of st_ifmt</returns>
private string Get_st_ifmt(string path)
{
Dictionary<string, string> fi = GetFileInfo(path);
return fi["st_ifmt"];
}
/// <summary>
/// Returns the size and type of the specified file or directory.
/// </summary>
/// <param name="path">The file or directory for which to retrieve information.</param>
/// <param name="size">Returns the size of the specified file or directory</param>
/// <param name="directory">Returns <c>true</c> if the given path describes a directory, false if it is a file.</param>
public void GetFileInfo(string path, out ulong size, out bool directory)
{
Dictionary<string, string> fi = GetFileInfo(path);
size = fi.ContainsKey("st_size") ? System.UInt64.Parse(fi["st_size"]) : 0;
bool SLink = false;
directory = false;
if (fi.ContainsKey("st_ifmt"))
{
switch (fi["st_ifmt"])
{
case "S_IFDIR": directory = true; break;
case "S_IFLNK": SLink = true; break;
}
}
if (SLink)
{
// test for symbolic directory link
IntPtr hAFCDir = IntPtr.Zero;
if (directory = (MobileDevice.DeviceImpl.DirectoryOpen(AFCCommsHandle, path, ref hAFCDir) == 0))
{
MobileDevice.DeviceImpl.DirectoryClose(AFCCommsHandle, hAFCDir);
}
}
}
/// <summary>
/// Returns the size of the specified file or directory.
/// </summary>
/// <param name="path">The file or directory for which to obtain the size.</param>
/// <returns></returns>
public ulong FileSize(string path)
{
bool is_dir;
ulong size;
GetFileInfo(path, out size, out is_dir);
return size;
}
/// <summary>
/// Creates the directory specified in path
/// </summary>
/// <param name="path">The directory path to create</param>
/// <returns>true if directory was created</returns>
public bool CreateDirectory(string path)
{
return !(MobileDevice.DeviceImpl.DirectoryCreate(AFCCommsHandle, FullPath(CurrentDirectory, path)) != 0);
}
/// <summary>
/// Gets the names of subdirectories in a specified directory.
/// </summary>
/// <param name="path">The path for which an array of subdirectory names is returned.</param>
/// <returns>An array of type <c>String</c> containing the names of subdirectories in <c>path</c>.</returns>
public string[] GetDirectories(string path)
{
if (!IsConnected)
{
Reconnect();
if (!IsConnected)
{
throw new Exception("Not connected to phone");
}
}
IntPtr hAFCDir = IntPtr.Zero;
string full_path = FullPath(CurrentDirectory, path);
//full_path = "/private"; // bug test
int res = MobileDevice.DeviceImpl.DirectoryOpen(AFCCommsHandle, full_path, ref hAFCDir);
if (res != 0)
{
throw new Exception("Path does not exist: " + res.ToString());
}
string buffer = null;
ArrayList paths = new ArrayList();
MobileDevice.DeviceImpl.DirectoryRead(AFCCommsHandle, hAFCDir, ref buffer);
while (buffer != null)
{
if ((buffer != ".") && (buffer != "..") && IsDirectory(FullPath(full_path, buffer)))
{
paths.Add(buffer);
}
MobileDevice.DeviceImpl.DirectoryRead(AFCCommsHandle, hAFCDir, ref buffer);
}
MobileDevice.DeviceImpl.DirectoryClose(AFCCommsHandle, hAFCDir);
return (string[])paths.ToArray(typeof(string));
}
/// <summary>
/// Moves a file or a directory and its contents to a new location or renames a file or directory if the old and new parent path matches.
/// </summary>
/// <param name="sourceName">The path of the file or directory to move or rename.</param>
/// <param name="destName">The path to the new location for <c>sourceName</c>.</param>
/// <remarks>Files cannot be moved across filesystem boundaries.</remarks>
public bool Rename(string sourceName, string destName)
{
return MobileDevice.DeviceImpl.RenamePath(AFCCommsHandle,
FullPath(CurrentDirectory, sourceName),
FullPath(CurrentDirectory, destName)) == 0;
}
/// <summary>
/// Returns the root information for the specified path.
/// </summary>
/// <param name="path">The path of a file or directory.</param>
/// <returns>A string containing the root information for the specified path. </returns>
public string GetDirectoryRoot(string path)
{
return "/";
}
/// <summary>
/// Determines whether the given path refers to an existing file or directory on the phone.
/// </summary>
/// <param name="path">The path to test.</param>
/// <returns><c>true</c> if path refers to an existing file or directory, otherwise <c>false</c>.</returns>
public bool Exists(string path)
{
TypedPtr<AFCDictionary> data = IntPtr.Zero;
int ret = MobileDevice.DeviceImpl.FileInfoOpen(AFCCommsHandle, path, out data);
if (ret == 0)
{
MobileDevice.DeviceImpl.KeyValueClose(data);
}
return ret == 0;
}
/// <summary>
/// Determines whether the given path refers to an existing directory on the phone.
/// </summary>
/// <param name="path">The path to test.</param>
/// <returns><c>true</c> if path refers to an existing directory or is a symbolic link to one, otherwise <c>false</c>.</returns>
public bool IsDirectory(string path)
{
bool is_dir;
ulong size;
GetFileInfo(path, out size, out is_dir);
return is_dir;
}
/// <summary>
/// Test if path represents a regular file
/// </summary>
/// <param name="path">path to query</param>
/// <returns>true if path refers to a regular file, false if path is a link or directory</returns>
public bool IsFile(string path)
{
return Get_st_ifmt(path) == "S_IFREG";
}
/// <summary>
/// Test if path represents a link
/// </summary>
/// <param name="path">path to test</param>
/// <returns>true if path is a symbolic link</returns>
public bool IsLink(string path)
{
return Get_st_ifmt(path) == "S_IFLNK";
}
/// <summary>
/// Deletes an empty directory from a specified path.
/// </summary>
/// <param name="path">The name of the empty directory to remove. This directory must be writable and empty.</param>
public void DeleteDirectory(string path)
{
string full_path = FullPath(CurrentDirectory, path);
if (IsDirectory(full_path))
{
MobileDevice.DeviceImpl.RemovePath(AFCCommsHandle, full_path);
}
}
/// <summary>
/// Deletes the specified directory and, if indicated, any subdirectories in the directory.
/// </summary>
/// <param name="path">The name of the directory to remove.</param>
/// <param name="recursive"><c>true</c> to remove directories, subdirectories, and files in path; otherwise, <c>false</c>. </param>
public void DeleteDirectory(string path, bool recursive)
{
if (!recursive)
{
DeleteDirectory(path);
return;
}
string full_path = FullPath(CurrentDirectory, path);
if (IsDirectory(full_path))
{
InternalDeleteDirectory(path);
}
}
/// <summary>
/// Deletes the specified file.
/// </summary>
/// <param name="path">The name of the file to remove.</param>
public void DeleteFile(string path)
{
string full_path = FullPath(CurrentDirectory, path);
if (Exists(full_path))
{
MobileDevice.DeviceImpl.RemovePath(AFCCommsHandle, full_path);
}
}
#endregion // Filesystem
#region Public Methods
/// <summary>
/// Close the AFC connection
/// </summary>
public void Disconnect()
{
if (AFCCommsHandle.Handle != IntPtr.Zero)
{
MobileDevice.DeviceImpl.ConnectionClose(AFCCommsHandle);
MobileDevice.DeviceImpl.StopSession(iPhoneHandle);
MobileDevice.DeviceImpl.Disconnect(iPhoneHandle);
}
AFCCommsHandle = IntPtr.Zero;
}
/// <summary>
/// Close and Reopen AFC Connection
/// </summary>
/// <returns>status from reopen</returns>
public void Reconnect()
{
Disconnect();
ConnectToPhone();
}
#endregion // public Methods
void CopyFileToPhone(string PathOnPC, string PathOnPhone)
{
CopyFileToPhone(PathOnPC, PathOnPhone, 1024 * 1024);
}
void CopyFileToPhone(string PathOnPC, string PathOnPhone, int ChunkSize)
{
DateTime StartTime = DateTime.Now;
byte[] buffer = new byte[ChunkSize];
// verify we are still connected
if (!IsConnected)
{
Reconnect();
}
// Make sure the directory exists on the phone
string DirectoryOnPhone = PathOnPhone.Remove(PathOnPhone.LastIndexOf('/'));
if (!IsDirectory(DirectoryOnPhone))
{
Console.WriteLine("Directory (" + DirectoryOnPhone + ") doesn't exist!");
if (!CreateDirectory(DirectoryOnPhone))
{
Console.WriteLine("CreateDirectory (" + DirectoryOnPhone + ") failed");
// throw new IOException("CreateDirectory (" + DirectoryOnPhone + ") failed");
}
}
FileStream SourceFile = File.OpenRead(PathOnPC);
iPhoneFile DestinationFile = iPhoneFile.OpenWrite(this, PathOnPhone);
long ProgressInterval = Math.Max(buffer.Length, (SourceFile.Length / TransferProgressDivisor));
long NextProgressPrintout = ProgressInterval;
long TotalBytesRead = 0;
int BytesRead = SourceFile.Read(buffer, 0, buffer.Length);
while (BytesRead > 0)
{
if (TotalBytesRead >= NextProgressPrintout)
{
NextProgressPrintout += ProgressInterval;
if (OnGenericProgress != null)
{
int PercentDone = (int)((100 * TotalBytesRead) / SourceFile.Length);
string Msg = "Transferred " + (SourceFile.Position / 1024) + " KB of " + (SourceFile.Length / 1024) + " KB";
OnGenericProgress(Msg, PercentDone);
}
else
{
Console.WriteLine(" ... Transferred " + (SourceFile.Position / 1024) + " KB of " + (SourceFile.Length / 1024) + " KB");
}
}
DestinationFile.Write(buffer, 0, BytesRead);
BytesRead = SourceFile.Read(buffer, 0, buffer.Length);
TotalBytesRead += BytesRead;
}
// DestinationFile.Flush();
DestinationFile.Close();
SourceFile.Close();
TimeSpan CopyLength = DateTime.Now - StartTime;
Console.WriteLine(" ... Finished copying to '{1}' in {0:0.00} s", CopyLength.TotalSeconds, PathOnPhone);
}
// Default level is 6, and 0,3,7 are regularly used. Bump the logging level up to 7 to get verbose logs.
void SetLoggingLevel(int Threshold)
{
Int32 LoggingThreshold = Math.Min(Math.Max(0, Threshold), 7);
MobileDevice.CoreImpl.CFPreferencesSetAppValue(
(IntPtr)MobileDevice.CFStringMakeConstantString("LogLevel"),
(IntPtr)MobileDevice.CFNumberCreate(LoggingThreshold),
(IntPtr)MobileDevice.CFStringMakeConstantString("com.apple.MobileDevice"));
}
void WriteProgressLine(string Fmt, int ProgressCount, params object[] Args)
{
string Line = String.Format(Fmt, Args);
if (OnGenericProgress != null)
{
OnGenericProgress(Line, ProgressCount);
}
else
{
Console.WriteLine(Line);
}
}
/// <summary>
/// Copies a file from the phone to the PC
/// </summary>
void CopyFileFromPhone(string PathOnPC, string PathOnPhone, int ChunkSize)
{
DateTime StartTime = DateTime.Now;
byte[] buffer = new byte[ChunkSize];
// Make sure the directory exists on the PC
string DirectoryOnPC = Path.GetDirectoryName(PathOnPC);
Directory.CreateDirectory(DirectoryOnPC);
iPhoneFile SourceFile = iPhoneFile.OpenRead(this, PathOnPhone);
FileStream DestinationFile = File.OpenWrite(PathOnPC);
long TotalBytesRead = 0;
int BytesRead = SourceFile.Read(buffer, 0, buffer.Length);
while (BytesRead > 0)
{
DestinationFile.Write(buffer, 0, BytesRead);
BytesRead = SourceFile.Read(buffer, 0, buffer.Length);
TotalBytesRead += BytesRead;
}
DestinationFile.Flush();
DestinationFile.Close();
SourceFile.Close();
TimeSpan CopyLength = DateTime.Now - StartTime;
WriteProgressLine(" ... Finished copying to '{1}' in {0:0.00} s", 100, CopyLength.TotalSeconds, PathOnPC);
}
string MakeUnixPath(string PlatformPath)
{
string Result = Path.GetFullPath(PlatformPath);
// Convert C:\ to /C\, the \ will get converted to / in the next step
if (Path.IsPathRooted(Result))
{
string Root = Path.GetPathRoot(Result);
Result = '/' + Root.Replace(":", "") + Result.Substring(Root.Length);
}
// Convert slash directions
if (Path.DirectorySeparatorChar != '/')
{
Result = Result.Replace(Path.DirectorySeparatorChar, '/');
}
return Result;
}
void ReconnectWithInstallProxy()
{
Reconnect();
if (MobileDevice.DeviceImpl.StartService(iPhoneHandle, MobileDevice.CFStringMakeConstantString("com.apple.mobile.installation_proxy"), ref hInstallService, IntPtr.Zero) != 0)
{
Console.WriteLine("Unable to start installation_proxy service!");
}
}
public delegate void ProgressCallback(string Message, int PercentDone);
public ProgressCallback OnGenericProgress = null;
public int TransferProgressDivisor = 25;
/// <summary>
/// Generic progress callback implementation (used for install/uninstall/etc...)
/// </summary>
void HandleProgressCallback(string OuterFunction, TypedPtr<CFDictionary> SourceDict)
{
Dictionary<string, object> Dict = MobileDevice.ConvertCFDictionaryToDictionaryString(SourceDict);
// Expecting:
// string,string -> "Status",PhaseOfInstaller
// string,number -> "PercentComplete",%Done
try
{
string Phase = Dict["Status"] as string;
int PercentDone = (int)((Double)(Dict["PercentComplete"]));
if (OnGenericProgress != null)
{
string Msg = String.Format("{0} is {1}% complete at phase '{2}'", OuterFunction, PercentDone, Phase);
OnGenericProgress(Msg, PercentDone);
}
else
{
Console.WriteLine(" ... {0} {1}% complete (phase '{2}')", OuterFunction, PercentDone, Phase);
}
}
catch (System.Exception)
{
}
}
/// <summary>
/// Progress callback for upgrading or installing
/// </summary>
void InstallProgressCallback(IntPtr UntypedSourceDict, IntPtr UserData)
{
HandleProgressCallback("Install", UntypedSourceDict);
}
/// <summary>
/// Progress callback for uninstalling
/// </summary>
void UninstallProgressCallback(IntPtr UntypedSourceDict, IntPtr UserData)
{
HandleProgressCallback("Uninstall", UntypedSourceDict);
}
/// <summary>
/// Try to install an IPA on the mobile device (it must have already been copied to the PublicStaging directory, with the same filename as the path passed in)
/// </summary>
public bool TryInstall(string IPASourcePathOnPC)
{
DateTime StartTime = DateTime.Now;
ReconnectWithInstallProxy();
IntPtr LiveConnection = IntPtr.Zero;
IntPtr ClientOptions = IntPtr.Zero;
TypedPtr<CFURL> UrlPath = MobileDevice.CreateFileUrlHelper(IPASourcePathOnPC, false);
// string UrlPathAsString = MobileDevice.GetStringForUrl(UrlPath);
int Result = MobileDevice.DeviceImpl.SecureInstallApplication(LiveConnection, iPhoneHandle, UrlPath, ClientOptions, InstallProgressCallback, IntPtr.Zero);
if (Result == 0)
{
Console.WriteLine("Install of \"{0}\" completed successfully in {2:0.00} seconds", Path.GetFileName(IPASourcePathOnPC), Result, (DateTime.Now - StartTime).TotalSeconds);
}
else
{
Console.WriteLine("Install of \"{0}\" failed with error code {1} in {2:0.00} seconds", Path.GetFileName(IPASourcePathOnPC), MobileDevice.GetErrorString(Result), (DateTime.Now - StartTime).TotalSeconds);
}
return Result == 0;
}
/// <summary>
/// Try to update an IPA on the mobile device (it must have already been copied to the PublicStaging directory, with the same filename as the path passed in)
/// </summary>
public bool TryUpgrade(string IPASourcePathOnPC)
{
DateTime StartTime = DateTime.Now;
ReconnectWithInstallProxy();
IntPtr LiveConnection = IntPtr.Zero;
IntPtr ClientOptions = IntPtr.Zero;
TypedPtr<CFURL> UrlPath = MobileDevice.CreateFileUrlHelper(IPASourcePathOnPC, false);
// string UrlPathAsString = MobileDevice.GetStringForUrl(UrlPath);
int Result = MobileDevice.DeviceImpl.SecureUpgradeApplication(LiveConnection, iPhoneHandle, UrlPath, ClientOptions, InstallProgressCallback, IntPtr.Zero);
if (Result == 0)
{
Console.WriteLine("Install \\ Update of \"{0}\" finished in {2:0.00} seconds", Path.GetFileName(IPASourcePathOnPC), Result, (DateTime.Now - StartTime).TotalSeconds);
}
else
{
Console.WriteLine("Install \\ Update of \"{0}\" failed with {1} in {2:0.00} seconds", Path.GetFileName(IPASourcePathOnPC), MobileDevice.GetErrorString(Result), (DateTime.Now - StartTime).TotalSeconds);
}
return Result == 0;
}
public bool TryUninstall(string ApplicationIdentifier)
{
DateTime StartTime = DateTime.Now;
ReconnectWithInstallProxy();
TypedPtr<CFString> CF_ApplicationIdentifier = MobileDevice.CFStringMakeConstantString(ApplicationIdentifier);
IntPtr CF_ClientOptions = IntPtr.Zero;
// IntPtr ExtraKey = IntPtr.Zero;
// IntPtr ExtraValue = IntPtr.Zero;
IntPtr ConnectionHandle = IntPtr.Zero;
int Result = MobileDevice.DeviceImpl.SecureUninstallApplication(ConnectionHandle, iPhoneHandle, CF_ApplicationIdentifier, CF_ClientOptions, UninstallProgressCallback, IntPtr.Zero);
if (Result == 0)
{
Console.WriteLine("Uninstall of \"{0}\" completed successfully in {2:0.00} seconds", ApplicationIdentifier, Result, (DateTime.Now - StartTime).TotalSeconds);
}
else
{
Console.WriteLine("Uninstall of \"{0}\" failed with {1} in {2:0.00} seconds", ApplicationIdentifier, MobileDevice.GetErrorString(Result), (DateTime.Now - StartTime).TotalSeconds);
}
return Result == 0;
}
/// <summary>
/// Copies a file to the PublicStaging directory on the mobile device, preserving the filename
/// </summary>
/// <param name="SourceFile"></param>
public void CopyFileToPublicStaging(string SourceFile)
{
string IpaFilename = Path.GetFileName(SourceFile);
CopyFileToPhone(SourceFile, "PublicStaging/" + IpaFilename);
//Dictionary<string, string> fi = GetFileInfo("/PublicStaging/" + IpaFilename);
}
public bool StartSyslogService()
{
if (MobileDevice.DeviceImpl.Connect(iPhoneHandle) != 0)
{
Console.WriteLine("Connect: Failed to Connect");
return false;
}
if (MobileDevice.DeviceImpl.StartSession(iPhoneHandle) == 1)
{
Console.WriteLine("Connect: Couldn't start session");
return false;
}
if (MobileDevice.DeviceImpl.SecureStartService(iPhoneHandle, MobileDevice.CFStringMakeConstantString("com.apple.syslog_relay"), 0, ref hSyslogService) != 0)
{
Console.WriteLine("Connect: Couldn't Start syslog relay service");
return false;
}
return true;
}
public string GetSyslogData()
{
return MobileDevice.DeviceImpl.ServiceConnectionReceive(hSyslogService);
}
public void StopSyslogService()
{
MobileDevice.DeviceImpl.StopSession(iPhoneHandle);
MobileDevice.DeviceImpl.Disconnect(iPhoneHandle);
}
#region Private Methods
public bool ConnectToPhone()
{
SetLoggingLevel(7);
// Make sure we can connect to the phone and that it has been paired with this machine previously
if (MobileDevice.DeviceImpl.Connect(iPhoneHandle) != 0)
{
Console.WriteLine("Connect: Failed to Connect");
return false;
}
if (MobileDevice.DeviceImpl.IsPaired(iPhoneHandle) != 1)
{
Console.WriteLine("Connect: Device is not paired");
return false;
}
if (MobileDevice.DeviceImpl.ValidatePairing(iPhoneHandle) != 0)
{
Console.WriteLine("Connect: Pairing not valid");
return false;
}
// Start a session
if (MobileDevice.DeviceImpl.StartSession(iPhoneHandle) == 1)
{
Console.WriteLine("Connect: Couldn't start session");
return false;
}
if (MobileDevice.DeviceImpl.StartService(iPhoneHandle, MobileDevice.CFStringMakeConstantString("com.apple.afc"), ref hService, IntPtr.Zero) != 0)
{
Console.WriteLine("Connect: Couldn't Start AFC service");
return false;
}
// Open a file sharing connection
if (MobileDevice.DeviceImpl.ConnectionOpen(hService, 0, out AFCCommsHandle) != 0)
{
Console.WriteLine("Connect: Couldn't Open File Sharing Connection");
return false;
}
connected = true;
return true;
}
public bool ConnectToBundle(string BundleName)
{
Reconnect();
TypedPtr<CFString> CFBundleName = MobileDevice.CFStringMakeConstantString(BundleName);
// Open the bundle
int Result = MobileDevice.DeviceImpl.StartHouseArrestService(iPhoneHandle, CFBundleName, IntPtr.Zero, ref hService, 0);
if (Result != 0)
{
Console.WriteLine("Failed to connect to bundle '{0}' with {1}", BundleName, MobileDevice.GetErrorString(Result));
return false;
}
// Open a file sharing connection
if (MobileDevice.DeviceImpl.ConnectionOpen(hService, 0, out AFCCommsHandle) != 0)
{
return false;
}
return true;
}
private void DfuConnectCallback(ref AMRecoveryDevice callback)
{
OnDfuConnect(new DeviceNotificationEventArgs(callback));
}
private void DfuDisconnectCallback(ref AMRecoveryDevice callback)
{
OnDfuDisconnect(new DeviceNotificationEventArgs(callback));
}
private void RecoveryConnectCallback(ref AMRecoveryDevice callback)
{
OnRecoveryModeEnter(new DeviceNotificationEventArgs(callback));
}
private void RecoveryDisconnectCallback(ref AMRecoveryDevice callback)
{
OnRecoveryModeLeave(new DeviceNotificationEventArgs(callback));
}
private void InternalDeleteDirectory(string path)
{
string full_path = FullPath(CurrentDirectory, path);
string[] contents = GetFiles(path);
for (int i = 0; i < contents.Length; i++)
{
DeleteFile(full_path + "/" + contents[i]);
}
contents = GetDirectories(path);
for (int i = 0; i < contents.Length; i++)
{
InternalDeleteDirectory(full_path + "/" + contents[i]);
}
DeleteDirectory(path);
}
static char[] path_separators = { '/' };
internal string FullPath(string path1, string path2)
{
if ((path1 == null) || (path1 == String.Empty))
{
path1 = "/";
}
if ((path2 == null) || (path2 == String.Empty))
{
path2 = "/";
}
string[] path_parts;
if (path2[0] == '/')
{
path_parts = path2.Split(path_separators);
}
else if (path1[0] == '/')
{
path_parts = (path1 + "/" + path2).Split(path_separators);
}
else
{
path_parts = ("/" + path1 + "/" + path2).Split(path_separators);
}
string[] result_parts = new string[path_parts.Length];
int target_index = 0;
for (int i = 0; i < path_parts.Length; i++)
{
if (path_parts[i] == "..")
{
if (target_index > 0)
{
target_index--;
}
}
else if ((path_parts[i] == ".") || (path_parts[i] == ""))
{
// Do nothing
}
else
{
result_parts[target_index++] = path_parts[i];
}
}
return "/" + String.Join("/", result_parts, 0, target_index);
}
#endregion // Private Methods
}
}